gotchareactMajorpending
React keys must be stable -- using array index causes bugs
Viewed 0 times
React keyindex as keystable keylist reorderstate bug
browser
Error Messages
Problem
Using array index as React key causes state to attach to wrong items when the list is reordered, filtered, or items are inserted/removed. Inputs show wrong values, animations glitch, and components do not unmount correctly.
Solution
Use stable, unique identifiers as keys: database IDs, UUIDs, or any value that is unique to the item and does not change between renders. Never use Math.random() as key (creates new key every render, destroying all state). Index is ONLY safe when: the list is static, never reordered, and never filtered.
Why
React uses keys to match old and new elements in lists. If the key changes, React unmounts and remounts the component. If the key stays but points to a different item, React reuses the old component state for the new item.
Revisions (0)
No revisions yet.