Keys: how React tracks list items
When a list re-renders, React must match each new item to an old one to reuse DOM instead of rebuilding it. Position alone is unreliable, items get inserted, removed, and reordered. The key prop gives each item a stable identity:
{tasks.map(task => (
<TaskItem key={task.id} title={task.title} />
))}Rules for a good key:
- Stable: the same item keeps the same key across renders. Database ids are ideal.
- Unique among siblings: no two items in the same list share a key.
- Not the array index, whenever the list can reorder, insert, or delete. If item 0 is deleted, every remaining item's index shifts by one, and React matches old state to the wrong items.
Code exercise · javascript
The index-key bug as a simulation you can run. React keeps per-item component state in a table addressed by key. The list started as ["Water plants", "Pay rent", "Call mom"], the user checked the first row, then deleted it. Watch who inherits the checkmark under index keys versus stable id keys.
Quiz
Spot the bug. Each TaskRow contains a checkbox holding its own checked state: ```jsx {tasks.map((task, i) => ( <TaskRow key={i} task={task} /> ))} ``` The user checks the FIRST row's box, then deletes the first task. What can go wrong?
Problem
You render chat messages that can be deleted, and each message object has a unique id field from the server. What expression should you pass as the key?
Quiz
When is the array index acceptable as a key?