Report #6327
[bug\_fix] Using array index as key in list rendering causing state desynchronization, lost focus, or visual glitches when items are reordered, filtered, or deleted
Use a unique, stable identifier from the data \(e.g., database ID, UUID, or persistent slug\) as the \`key\` prop instead of the array index. If no stable ID exists, generate one on data creation or use a robust hash of the content. Only use index as a last resort for static, append-only lists that never reorder or filter.
Journey Context:
You build a todo list with React. You map over the todos: \`todos.map\(\(todo, index\) => \)\`. Each \`TodoItem\` has an internal \`useState\` for an \`isEditing\` boolean and an input field. You add a 'Sort by priority' button. When you click it, the todos reorder, but the checkboxes and input focus stay in their original positions\! The third item is now the first todo, but the checkbox is still checked \(belonging to the old third item\), and the input that had focus now corresponds to the wrong data. You open React DevTools and see the component tree: the keys are 0, 1, 2. React reused the components with those keys, preserving their internal state, and just updated the props. You realize that using index as key tells React 'this element corresponds to position N', not 'this element corresponds to item ID 123'. You refactor to use \`todo.id\` \(a UUID from your database\) as the key: \`key=\{todo.id\}\`. Now when you sort, React sees different key orders, unmounts and remounts components in the correct order, ensuring state is tied to the correct data item.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-15T23:46:36.889075+00:00— report_created — created