Lists & Keys
EasyRendering lists is fundamental to React applications. The key prop helps React identify which items changed, were added, or removed during reconciliation. Using stable, unique keys is critical for correct behavior and performance.
Interactive Visualization
Key Points
- Use .map() to transform arrays into lists of JSX elements
- Every element in a list needs a unique key prop
- Keys must be stable, unique among siblings, and not change between renders
- Database IDs or UUIDs make good keys; array indices do not for dynamic lists
- Using index as key causes bugs when items are reordered, inserted, or deleted
- Keys are not passed as props to the child component
- React uses keys to match old and new elements during reconciliation
Code Examples
Rendering a List with Keys
interface Todo { id: string text: string completed: boolean } interface TodoListProps { todos: Todo[] onToggle: (id: string) => void } function TodoList({ todos, onToggle }: TodoListProps) { return ( <ul> {todos.map((todo) => ( <li key={todo.id} onClick={() => onToggle(todo.id)} style={{ textDecoration: todo.completed ? 'line-through' : 'none' }} > {todo.text} </li> ))} </ul> ) }
Each list item uses the todo.id as its key, letting React track items correctly even when the list is reordered
Why Index Keys Break
// BAD: index as key causes state mismatches on reorder function BadList({ items }: { items: string[] }) { return ( <ul> {items.map((item, index) => ( <li key={index}> <input defaultValue={item} /> </li> ))} </ul> ) } // GOOD: stable ID preserves state correctly function GoodList({ items }: { items: { id: string; text: string }[] }) { return ( <ul> {items.map((item) => ( <li key={item.id}> <input defaultValue={item.text} /> </li> ))} </ul> ) }
When items reorder, index keys make React match the wrong item to the wrong DOM node, causing input values to stick to the wrong rows
Common Mistakes
- Using array index as key for lists that can be reordered or filtered
- Using non-unique keys like item.name when names can repeat
- Generating keys with Math.random() which changes every render and destroys all state
Interview Tips
- Explain the reconciliation algorithm and why keys help React diff efficiently
- Describe concrete bugs that happen with index keys in dynamic lists
- Know that keys only need to be unique among siblings, not globally