Part 04 / Topic 3 of 8
The index-as-key bug, reproduced for real
The array index (items.map((item, index) => <li key={index}>...)) looks like a unique key - it is, in the sense that no two siblings ever share one - but it is not stable: index 1 means "Dosa" one render and "Vada" the next, the moment anything before it is removed, inserted, or reordered. React only ever compares old-key-at-this-position to new-key-at-this-position; it has no idea order.id exists unless you tell it to look there.
examples/02_key_prop_bug.jsx makes this a real, clickable bug instead of a warning. Three kitchen orders (Idli, Dosa, Vada) each get an uncontrolled note <input> - uncontrolled on purpose, so its typed text lives in the real DOM node, not in a piece of React state the next render would recompute anyway:
// examples/02_key_prop_bug.jsx (broken version, trimmed)
export function OrderNotesBrokenKey() {
const [orders, setOrders] = useState(initialOrders);
return (
<div>
<button onClick={() => setOrders((current) => current.slice(1))}>Mark first order served</button>
<ul>
{orders.map((order, index) => (
<OrderRow key={index} order={order} />
))}
</ul>
</div>
);
}
examples/02_key_prop_bug.test.jsx drives this with real user actions (@testing-library/user-event, not a bare assertion): type a note while "Dosa" sits at index 1, then click the button that removes the first order (Idli). This really runs, and really shows:
1. Type "extra chutney" into the note next to "Dosa" (index 1).
2. Click "Mark first order served" -> Idli is removed; Dosa shifts to
index 0, Vada shifts to index 1.
3. The note next to "Dosa" (now at index 0) is EMPTY - index 0's DOM node
used to be Idli's, and Idli's note was always blank.
4. The note next to "Vada" (now at index 1) reads "extra chutney" - index
1's DOM node is the one Dosa's note was typed into, and React reused
that exact node because the key at position 1 ("1") matched on both
renders. A kitchen staffer reading this screen would add extra chutney
to Vada's plate instead of Dosa's.
examples/02_key_prop_bug.jsx also exports OrderNotesFixedKey, identical except for one line - key={order.id} instead of key={index}. Run through the exact same steps (examples/02_key_prop_bug.test.jsx), it really shows the fix: Idli's <li> is removed outright (not reused, not emptied), Dosa's note stays with Dosa, and Vada's note stays blank, because React can now see that Dosa and Vada are the same two orders they always were.
๐ Going deeper: this is the same "React compares a new value to an old one" idea Part 2's props-are-read-only section raised for
useState.keyis that comparison applied one level up - per list item, not per component.
Done here? The practice set for Part 4 โ including the solutions โ is on the part page.