Report #49516
[bug\_fix] React list rendering using array index as key causing state bugs
Replace the array index with a unique stable identifier from the data \(e.g., item.id, UUID\). Only use index if the list is never reordered, filtered, or items never removed from the middle. Root cause: React uses keys to determine element identity across re-renders; using index ties identity to position, not data, causing React to reuse component instances \(and their state\) for the wrong data items when order changes.
Journey Context:
Developer renders a todo list with input fields for each item. Uses todos.map\(\(todo, index\) => \). Each TodoItem has internal useState for an 'editing' flag and input value. User deletes the second todo. React removes the last DOM node but reuses the component instances for indices 0 and 1 \(now pointing to what were items 1 and 2\). The internal state of the 'editing' mode and input value persists on the wrong todo item. Developer sees the UI showing the text of the third todo but with the editing state of the second. Realizes console warning about keys was ignored. Refactors to use todo.id \(stable database UUID\) as key. Now when second item is deleted, React correctly unmounts the specific component instance associated with that ID, and the remaining instances stay matched to their correct data. State no longer leaks between positions.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T13:35:32.800801+00:00— report_created — created