Chapter 9: Lists and Keys
Chapter 9 of 15
Chapter 9: Lists and Keys
9.1 Rendering Lists
Render lists of data using map() to create arrays of elements.
function FruitList() {
const fruits = ['Apple', 'Banana', 'Orange'];
return (
<ul>
{fruits.map((fruit, index) => (
<li key={index}>{fruit}</li>
))}
</ul>
);
}
Rendering Objects:
function UserList() {
const users = [
{ id: 1, name: 'John', email: 'john@example.com' },
{ id: 2, name: 'Jane', email: 'jane@example.com' }
];
return (
<ul>
{users.map(user => (
<li key={user.id}>
{user.name} - {user.email}
</li>
))}
</ul>
);
}
Complex List Rendering:
function ProductList({ products }) {
return (
<div className="product-grid">
{products.map(product => (
<ProductCard
key={product.id}
product={product}
/>
))}
</div>
);
}
9.2 Keys
Keys help React identify which items have changed, been added, or removed. They're essential for efficient list updates.
Why Keys Matter:
- Help React track items efficiently
- Prevent unnecessary re-renders
- Maintain component state correctly
- Improve performance
// Good: Use unique, stable IDs
{users.map(user => (
<UserCard key={user.id} user={user} />
))}
// Acceptable: Use index if no IDs (not ideal)
{items.map((item, index) => (
<Item key={index} item={item} />
))}
// Bad: Don't generate keys in render
{items.map(item => (
<Item key={Math.random()} item={item} /> // Wrong!
))}
Key Best Practices:
- Use unique IDs when available
- Keys should be stable (don't change)
- Don't use index if items can be reordered
- Keys only needed in the array context
9.3 Filtering and Transforming Lists
Filter and transform data before rendering.
function ActiveUsers({ users }) {
const activeUsers = users.filter(user => user.isActive);
return (
<ul>
{activeUsers.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
// Or inline
{users
.filter(user => user.isActive)
.map(user => <li key={user.id}>{user.name}</li>)
}
9.4 List Rendering Best Practices
Follow best practices for efficient list rendering.
- Always provide keys
- Use stable, unique keys
- Extract list items to components when complex
- Optimize with React.memo for large lists
- Consider virtualization for very long lists