Report #9461
[bug\_fix] Using array index as React key causing state preservation issues
Use a stable unique identifier from the data \(like item.id\) as the key prop instead of the array index. If no ID exists, generate a stable ID when creating the data array \(e.g., using uuid or a counter\), never using Math.random\(\) as that defeats the purpose.
Journey Context:
You build a todo list where users can add, delete, and reorder items. You render the list using todos.map\(\(todo, index\) => \). Each TodoItem has internal useState for an 'isEditing' toggle. Users report that when they delete a todo in the middle of the list, the wrong item appears to be deleted—the UI shows the text of the next item, but the editing state of the deleted item persists. You inspect with React DevTools and see that the component instance is being reused incorrectly. You realize that when you delete index 1, index 2 becomes the new index 1. Because you used key=\{index\}, React sees the same key and assumes it's the same component instance, preserving the internal 'isEditing' state. The fix is using todo.id as the key. This ensures React correctly identifies that the item with that specific ID was removed, unmounting the component and its state entirely, while properly mounting the new component instance for the remaining items. This works because React's reconciliation algorithm uses keys to establish component identity across renders; stable keys ensure identity is tied to the data entity, not its position in the array.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T08:15:25.349524+00:00— report_created — created