Keys and Lists
Rendering lists, key prop, stable keys, and reconciliation patterns.
Overview
Keys help React identify which items have changed, been added, or removed in lists.
Key Concepts
- key Prop — Unique identifier for list items
- Stable Keys — Use IDs, not array indices
- Reconciliation — React's algorithm for updating the DOM
- Fragment Keys — Keys needed when rendering lists inside fragments
- Performance — Proper keys prevent unnecessary re-renders
Code Examples
function TodoList({ todos }) {
return (
<ul>
{todos.map(todo => (
<li key={todo.id}>
<input type="checkbox" checked={todo.completed} readOnly />
<span style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}>
{todo.text}
</span>
</li>
))}
</ul>
);
}
// Bad: Using index as key
{items.map((item, index) => (
<ListItem key={index} item={item} />
))}
// Good: Using stable ID
{items.map(item => (
<ListItem key={item.id} item={item} />
))}
Practice
Build a sortable list that maintains correct state when items are reordered.