Topic 12 of 54
Why Keys Matter in Lists
Overview
When you render a list using `.map()`, React demands that you pass a special `key` prop to the outermost element. Keys help React identify which items have changed, been added, or been removed. Without a unique key, React's Virtual DOM diffing algorithm has to guess, which can lead to catastrophic bugs where the wrong UI is updated, deleted, or re-rendered slowly.
Syntax
Always use a unique identifier from your data (like a database ID). The key must be unique among its siblings.
Using IDs as Keys
jsx
// ✅ GOOD: Using a unique database ID as a key
<ul>
{users.map(user => (
<li key={user.userId}>{user.name}</li>
))}
</ul>
// ❌ BAD: Using the array index as a key (if the list can change)
<ul>
{users.map((user, index) => (
<li key={index}>{user.name}</li>
))}
</ul>Common Pitfalls
- Using `Math.random()` as a key. This forces React to completely destroy and recreate the elements on EVERY render, obliterating performance and local state.
- Placing the `key` prop on a child element instead of the outermost returned element inside the `.map()`.
Interview Tips
- Extremely common interview question: 'Why shouldn't you use the array index as a key?' Answer: If the list is reordered, items are inserted, or deleted, the indexes shift. This confuses React, causing it to map old state to new components, resulting in bugs like the wrong checkbox remaining checked.
Real-World Example
If you have a sortable list or a list where items can be deleted, using indexes as keys will break the UI state.
example
jsx
function ShoppingCart({ items, onRemove }) {
return (
<div>
{items.map(item => (
// Because item.id is stable and unique, React knows EXACTLY
// which item was removed when onRemove is clicked.
<div key={item.id} className="cart-item">
<span>{item.name}</span>
<button onClick={() => onRemove(item.id)}>Remove</button>
</div>
))}
</div>
);
}