Keys and Component State Preservation
What you'll learn: How stable keys ensure React preserves component instance state (like focus, scroll position, and useState values) when list items reorder.
Why Keys Affect Internal State
When React renders a list, it uses keys to determine if a component is the same instance being moved, or a different component that happens to be in that position now. If the key stays the same across renders, React preserves the component's internal state. If the key changes, React destroys the old component and creates a new one from scratch.
Think of keys like name tags at a party. If someone moves to a different seat but keeps their name tag, you know it's the same person. If they get a new name tag, you'd treat them as a different guest entirely.
What Gets Preserved (or Lost)
When keys are stable:
useStatevalues survive reordering- Input focus remains on the same logical item
- Scroll positions within nested components persist
- Controlled component values stay intact
When keys change unexpectedly (like using array index on a shuffled list):
- All internal state resets to initial values
- Focus jumps to the wrong element
- Animations restart
- User input gets lost
The Practical Impact
Imagine a todo list where each item has an "edit mode" controlled by local useState. If you sort the list using indices as keys, every item exits edit mode because React thinks they're all new components. With stable ID-based keys, items maintain their edit state even when reordered.
Key Takeaway: Stable keys are React's signal that "this is the same component, just in a new position" — ensuring state preservation, proper focus management, and smooth user experiences during list changes.