Keys Preserve Component Identity
What you'll learn: How React uses keys to decide whether to reuse an existing component or destroy and create a new one during list updates.
The Core Mechanism
When your list changes (items reordered, added, or removed), React doesn't just blindly recreate everything. It uses keys to track which component instance corresponds to which data item.
Think of keys like student ID numbers in a classroom. If you rearrange students' seats but track them by ID, you know Sarah is still Sarah even though she moved from seat 3 to seat 7. Without IDs, you might think the person now in seat 3 is Sarah when it's actually a completely different student.
Identity Determines What Survives
When React reconciles a list:
- Same key in same position → React reuses the existing component instance. Its state, DOM nodes, and internal timers survive.
- Key disappears → React destroys that component instance entirely. State is lost,
useEffectcleanup runs. - New key appears → React creates a fresh component instance from scratch. New state, new DOM, mounting logic runs.
- Same key in different position → React moves the existing instance without destroying it.
Why This Matters
Component identity affects:
- State persistence: A reused component keeps its local state
- DOM references: Input focus, scroll position, animations stay intact
- Performance: Reusing instances is faster than destroying and recreating
- Lifecycle: Mounting/unmounting hooks only run when identity actually changes
Key Takeaway: Keys are React's mechanism for tracking component identity across renders. The same key means "this is the same component," triggering reuse; a different key means "this is a different component," triggering full recreation.