Clean β’ Professional
In React, lists allow you to render multiple items dynamically β like products, users, or messages. To render lists efficiently, React uses keys to identify elements and optimize updates.
Understanding lists and keys is essential for performance, readability, and dynamic UI development.
React makes it easy to render arrays using JavaScriptβs map() method.
Example β Simple List Rendering
import React from "react";
function NameList() {
const names = ["Alice", "Bob", "Charlie"];
return (
<ul>
{names.map((name) => (
<li>{name}</li>
))}
</ul>
);
}
export default NameList;
map() creates a new <li> for each item.{} embed JavaScript inside JSX.Keys are unique identifiers for elements in a list. They help React track changes, additions, or deletions without re-rendering the entire list.
Example β Adding Keys
function NameList() {
const names = ["Alice", "Bob", "Charlie"];
return (
<ul>
{names.map((name, index) => (
<li key={index}>{name}</li>
))}
</ul>
);
}
Example β Using Unique IDs
React can now efficiently track which items changed when the list updates.
const users = [
{ id: 101, name: "Alice" },
{ id: 102, name: "Bob" },
{ id: 103, name: "Charlie" },
];
function UserList() {
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
Sometimes, a list item contains multiple elements, like a title and description. React Fragments help avoid unnecessary <div> wrappers.
Example β Fragment with Keys
key for React to track changes.const products = [
{ id: 1, name: "Laptop", price: "$1000" },
{ id: 2, name: "Phone", price: "$500" },
];
function ProductList() {
return (
<>
{products.map((product) => (
<React.Fragment key={product.id}>
<h3>{product.name}</h3>
<p>Price: {product.price}</p>
</React.Fragment>
))}
</>
);
}
You can combine lists with conditional rendering for dynamic UIs.
Example β Filtering List Items
filter() removes offline users.map() renders only the filtered users.const users = [
{ id: 1, name: "Alice", online: true },
{ id: 2, name: "Bob", online: false },
{ id: 3, name: "Charlie", online: true },
];
function OnlineUsers() {
return (
<ul>
{users
.filter((user) => user.online)
.map((user) => (
<li key={user.id}>{user.name} is online</li>
))}
</ul>
);
}
React efficiently updates lists thanks to keys. Only the changed elements re-render β improving performance for large datasets.
Example β Dynamic List Update
import React, { useState } from "react";
function TodoList() {
const [tasks, setTasks] = useState([
{ id: 1, text: "Buy groceries" },
{ id: 2, text: "Walk the dog" },
]);
const addTask = () => {
const newTask = { id: Date.now(), text: "New Task" };
setTasks([...tasks, newTask]);
};
return (
<div>
<button onClick={addTask}>Add Task</button>
<ul>
{tasks.map((task) => (
<li key={task.id}>{task.text}</li>
))}
</ul>
</div>
);
}
export default TodoList;
setTasks updates the array.key to re-render only the new task.