Sub topic 5
Choosing good keys: ids, not indexes
This chapter assumes you can write function components, pass props, use useState, and call map on an array. You should already know that React asks for a key on each list item. Here you will learn which values make good keys and what goes wrong with bad ones.
What a key does
React uses a key to match an item in the previous render with an item in the next render. If the key is the same, React treats it as the same item. It keeps that item's DOM node and any component state, and updates only what changed. If the key is new, React creates the item. If a key is missing, React removes the item.
A good key identifies the data, not the position. Position changes when you insert, remove, or reorder items. Identity does not.
Use a stable id from your data
Pick a value that is unique among siblings and stays the same for that item across renders. A database id, a UUID, or a slug works well.
const people = [
{ id: 1, name: 'Ada' },
{ id: 2, name: 'Grace' },
];
function PeopleList() {
return (
<ul>
{people.map(person => (
<li key={person.id}>{person.name}</li>
))}
</ul>
);
}Keys only need to be unique among siblings in the same list. Two different lists can reuse the same values.
Why the array index goes wrong
The index is the position, so it changes whenever the list is reordered or an item is inserted or removed. Suppose each row holds an input with its own state, and you key by index.
- The list is
[Ada, Grace], with keys0and1. - You remove Ada. The list is now
[Grace]. - Grace now has key
0. React sees key0still exists and reuses the first row's instance, including whatever the user typed into it. It then discards the row with key1.
The visible result is that text typed next to Ada now appears next to Grace. Nothing throws an error. The bug shows up only as wrong data on screen.
When the index is acceptable
Index keys are safe only when all of these hold:
- The list is static. It is never reordered, filtered, or edited.
- Items have no state of their own and no inputs.
- Items have no stable id to use.
If you are unsure, assume the index is not safe.
Common errors
| Mistake | Problem | Fix |
|---|---|---|
| `key={Math.random()}` | A new key every render, so React remounts every item and loses state and focus. | Use an id that already exists in the data. |
| `key={index}` on an editable list | State attaches to the wrong item after a reorder or removal. | Key by id. |
| Key set on the inner element, not the one returned by `map` | React warns about missing keys. | Put the key on the outermost element returned by the callback. |
| Duplicate keys among siblings | Items can be duplicated or dropped on update. | Make each key unique. |
Creating ids for new items
If data has no id, assign one once, when the item is created. Do not generate it during render.
import { useState } from 'react';
function Names() {
const [names, setNames] = useState([]);
function add(name) {
setNames([...names, { id: crypto.randomUUID(), name }]);
}
return (
<>
<button onClick={() => add('New person')}>Add</button>
<ul>
{names.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</>
);
}Because the id is stored with the item, it is the same on every render.
Exercise
A list of editable rows is keyed by index. The user deletes the first row, and the text they typed in that row now appears in the second row's place. Why does this happen, and what is the fix?
Show answer
After the deletion, the remaining item shifts to index 0. React matches by key, so it reuses the first row's component instance and state for that item. Key each row by a stable id stored in the data, such as key={row.id}, so state follows the item.