React / 19
Keys: how React tells list items apart
A key is a stable, unique name for each item in a list. React uses it to match items between renders, so DOM and state stay with the right item.
What React does with keys
After a re-render, React lines up the new list against the old one:
- Same key in both: same item. React keeps its DOM node and state, and updates only what changed.
- Key only in the new list: a new item. React creates it.
- Key only in the old list: a removed item. React destroys it, along with its state.
key = index
Tasty Bites → Dosa Corner
same key, so reused + relabelled
Green Bowl → Tasty Bites
same key, so reused + relabelled
(new) → Green Bowl
created
key = id
(new) → Dosa Corner
created
Tasty Bites → Tasty Bites
kept, untouched
Green Bowl → Green Bowl
kept, untouched
See the bug for yourself
Each row below keeps its note in its own state, set once when the row is created. So the note shows exactly which row React kept.
Index keys vs id keys
Try ititems.map((item, index) => <Row key={index} … />)- Tasty Bites
- Green Bowl
- Spice Route
With key={index}, the new item gets key 0, which used to belong to Tasty Bites. React thinks row 0 just had its name changed, so it reuses the old row, along with its state. Every note slides onto the wrong restaurant. With key={item.id}, React sees one new key and inserts one new row.
What makes a good key
| Key | Verdict |
|---|---|
An id from your data (item.id, a database id, a SKU, a slug) | Best. Unique and stable. |
| The array index | OK only if the list never reorders, inserts, deletes or filters. |
Math.random() or crypto.randomUUID() called during render | Never. A new key on every render remounts every item. |
| A name or title | Only if it's guaranteed unique. Two "Green Bowl" branches break it. |
Two rules:
- Unique among siblings. Keys only need to be unique inside one list. Two different lists can both use
"r1". - Stable. The same item must get the same key on every render.
If your data has no id, create one when the item is created (for example, crypto.randomUUID() when the user adds a todo) and store it with the item. Never generate it while rendering.
Where the key goes
Put it on the outermost element returned from map:
Don't
Key inside the component
function RestaurantCard({ r }) {
return <div key={r.id}>{r.name}</div>; // React ignores this for the list
}
restaurants.map((r) => <RestaurantCard r={r} />);Do
Key where map returns
function RestaurantCard({ r }) {
return <div>{r.name}</div>;
}
restaurants.map((r) => <RestaurantCard key={r.id} r={r} />);Returning several elements per item? Wrap them in <Fragment key={r.id}> (import Fragment from "react"). The short <>…</> syntax can't take a key.
Gotchas
Recall
Can you answer these?
0/5
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
