React Lists & Keys
Lists are a fundamental concept in React that allow rendering multiple elements dynamically. React efficiently updates and renders lists using a special attribute called keys.
Rendering Lists in React
You can render a list by mapping over an array and returning JSX elements.
👉 Example: Rendering a List of Items
function ItemList() {
const items = [“Apple”, “Banana”, “Cherry”];
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);
}
📝 Explanation
✔ The items array ([“Apple”, “Banana”, “Cherry”]) is created.
✔ .map() loops over the array and returns <li> elements for each item.
✔ Each <li> gets a unique key (index) to help React track changes.
✔ React converts JSX to Virtual DOM and efficiently updates the real DOM.
📌 Best Practice: Using index as a key is not recommended unless the list items are static and never change order.
Importance of Keys in Lists
Keys help React efficiently update the UI when elements are added, removed, or reordered.
Why Use Keys?
✔️ Improve Performance: Prevent unnecessary re-renders.
✔️ Help React Track Items: Maintain element identity.
✔️ Provide Stability: Ensure UI consistency.
👉 Example: Using Unique Keys
function UserList() {
const users = [
{ id: 101, name: “Alice” },
{ id: 102, name: “Bob” },
{ id: 103, name: “Charlie” }
];
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
📝 Explanation
✔ The users array contains objects with unique id and name.
✔ .map() loops over users, creating <li> elements for each user.
✔ The key is set to user.id (a unique value) instead of the index.
✔ Why? Using a unique key helps React efficiently update the DOM.
📌 Best Practice: Use a unique id as the key instead of the array index.
Rendering Lists of Components
Lists can be used to render multiple instances of a component dynamically.
👉 Example: Rendering a List of Components
function User({ name }) {
return <li>{name}</li>;
}
function UserList() {
const users = [“Alice”, “Bob”, “Charlie”];
return (
<ul>
{users.map((user, index) => (
<User key={index} name={user} />
))}
</ul>
);
}
📝 Explanation
✔ User Component: A separate component that takes name as a prop and renders an <li>.
✔ UserList Component:
• Defines an array of users.
• Uses .map() to create multiple <User /> components.
• Passes each user name as a prop.
✔ Why Component-Based?
• Improves code reusability.
• Makes it easier to manage complex lists.
📌 Tip: When possible, pass unique identifiers as keys.
Conditional Rendering in Lists
You can dynamically filter, modify, or conditionally render list elements.
👉 Example: Filtering and Displaying Items
function TaskList() {
const tasks = [
{ id: 1, title: “Learn React”, completed: true },
{ id: 2, title: “Build a Project”, completed: false }
];
return (
<ul>
{tasks.map(task =>
task.completed ? <li key={task.id}>{task.title}</li> : null
)}
</ul>
);
}
📝 Explanation
✔ tasks Array: Contains a list of tasks with id, title, and completed status.
✔ .map() Method: Loops through the tasks array.
✔ Filtering Logic:
• If task.completed is true, render <li> with the task title.
• If false, return null (skips rendering).
📌 Best Practice: Use .filter() before .map() for better efficiency.
Handling Dynamic Lists (Adding & Removing Items)
Lists often change during runtime, requiring state management.
👉 Example: Adding Items to a List
👉 Example: Adding Items to a Listimport { useState } from ‘react’;
function DynamicList() {
const [items, setItems] = useState([“Apple”, “Banana”]);
function addItem() {
setItems([…items, Item ${items.length + 1}]);
}
return (
<div>
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
<button onClick={addItem}>Add Item</button>
</div>
);
}
📝 Explanation
✔ useState Hook: Manages the items list (initially [“Apple”, “Banana”]).
✔ addItem Function:
• Creates a new item: “Item X” (X is the next number in the list).
• Uses setItems([…items, newItem]) to update the state.
✔ Rendering the List:
• .map() loops through items, displaying each in <li>.
✔ Button Click (onClick): Calls addItem(), adding a new item to the list.
📌 Tip: Always update state immutably (setItems([…items, newItem])).
Conclusion
✅ Lists enable rendering multiple items dynamically.
✅ Keys help React optimize rendering by tracking element identity.
✅ Use unique identifiers as keys instead of indexes.
✅ Apply conditional rendering and manage dynamic lists effectively.