Why Keys Must Be Stable Across Renders
What you'll learn: How changing keys between renders breaks React's ability to track components and causes unexpected bugs.
The Core Problem
When you render a list in React, each item needs a key prop so React can tell which element is which across re-renders. But here's the critical requirement: the key for a specific item must stay the same between renders.
If the key changes, React thinks the old item was deleted and a completely new item was created, even if it's actually the same data. This causes:
- Lost component state (scroll position, focus, local state variables)
- Unnecessary unmounting and remounting (performance hit)
- Broken animations (elements appear to "restart")
- Re-triggered effects (useEffect cleanup and re-run)
The Analogy
Imagine a teacher taking attendance. If students kept changing their names every day, the teacher couldn't track who was present yesterday vs today. She'd mark everyone absent and create new records, losing all history. Keys work the same way—they're the "stable name" React uses to track identity.
Common Anti-Pattern: Using Index When Order Changes
// ❌ BAD: If items reorder, indices change
items.map((item, index) => <Item key={index} data={item} />)
// ❌ WORSE: Key changes every render!
items.map(item => <Item key={Math.random()} data={item} />)
// ✅ GOOD: Stable identifier from data
items.map(item => <Item key={item.id} data={item} />)
The key must be derived from something that doesn't change for that specific piece of data—usually a unique ID from your backend.
Key Takeaway: Keys must remain consistent across renders for the same logical item. Changing keys forces React to destroy and recreate components, losing all internal state and triggering unnecessary work.