Index-as-Key Reordering Bug
You'll learn: How using array indices as keys causes React to display wrong data when list items reorder.
The Classic Reordering Bug
When you use array indices as keys (key={index}), React thinks the position identifies the component, not the data. When items reorder, React reuses components at each position but swaps the data props—causing component state and DOM state to stick to the wrong items.
The Coffee Order Analogy
Imagine a barista who labels orders by position: "First", "Second", "Third". When someone moves from third to first place in line, the barista still calls them "Third" and gives them the wrong coffee—because the label stayed with the position, not the person.
What Actually Happens
// Items start: [{id: 'a', text: 'Apple'}, {id: 'b', text: 'Banana'}]
items.map((item, index) => (
<TodoItem key={index} text={item.text} />
))
// React sees: key=0, key=1
// After reordering: [{id: 'b', text: 'Banana'}, {id: 'a', text: 'Apple'}]
// React STILL sees: key=0, key=1
// React thinks: "Same keys! Just update the props!"
// But component state (checkbox, input focus, etc.) stays at key=0!
React updates the text prop but preserves the component instance. If TodoItem had an internal checked state or focused input, that state stays with key=0—now pointing at the wrong item.
The Real-World Pain
This manifests as checked checkboxes appearing on wrong items, form inputs showing wrong values, or focus jumping to incorrect elements after drag-and-drop or sorting operations.
Key Takeaway: Index keys break when lists reorder because React matches keys by position, not data identity—always use stable IDs to prevent state misalignment.