Keys Must Be Stable Across Renders
What you'll learn: Why using the same key for the same item across re-renders is critical for React to preserve component state and behavior.
The Core Problem
You already know that keys must be unique among siblings to help React identify which items are which. But there's a second requirement that's equally important: the key for a given item must remain the same every time your component re-renders.
If you generate a new key on each render (like using Math.random() or a timestamp), React sees it as a completely different item. This causes React to unmount the old component and mount a brand new one—wiping out any internal state, resetting form inputs, losing focus, and triggering unnecessary re-renders.
A Real-World Analogy
Imagine you're a teacher tracking students in your class. If every day you assign each student a random new ID number, you'd have no way to know that "Student #42" today is the same person as "Student #91" yesterday. You'd lose track of their grades, attendance, and progress. Stable identifiers let you maintain continuity.
What Stable Means
A stable key is one that doesn't change between renders for the same logical item:
- Good: Database IDs, unique product SKUs, usernames—values tied to the data itself
- Bad:
Math.random(),Date.now(), generating UUIDs on each render - Risky: Array indexes (stable only if the list never reorders)
When your data doesn't have natural IDs, generate stable keys once (when data is loaded) and store them, rather than creating new keys every render.
Key Takeaway: A key must remain constant for the same item across renders so React can preserve component state, maintain focus, and avoid unnecessary remounting.