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 to render a list. You have already seen that each list item needs a key. Here you will learn how to choose it. The choice looks minor, but a wrong key can make a list show the wrong data without any error.
What React does with a key
When a list re-renders, React has to decide which new element corresponds to which old element. The key is how it matches them. React does not compare positions in the array. It compares keys.
- If a key appears in both the old and new render, React reuses that element's component instance, including its state, and updates its props.
- If a key is new, React creates a new instance.
- If a key disappeared, React destroys that instance and its state.
So a key is not a label for the DOM. It is the identity of an item. A good key answers the question "which item is this?" the same way on every render.
The three properties of a good key
A good key is:
- Unique among its siblings. Two items in the same array must never share a key. Keys only need to be unique within one list, not across the whole app.
- Stable. The same item gets the same key on every render, even if its position changes.
- Tied to the item's data. The key comes from the data, not from where the item sits or from a value generated while rendering.
Index keys fail property 2 and property 3 whenever the list can change order, grow at the front, or shrink from the middle. Math.random() or crypto.randomUUID() called inside render fails property 2 on every render.
Seeing the index bug
The component below keeps a private note for each row. The note lives in the row's own state, so it belongs to the component instance, not to the task data. The list uses the array index as the key.
import { useState } from 'react';
function Row({ title }) {
const [note, setNote] = useState('');
return (
<li>
{title}{' '}
<input
value={note}
placeholder="note"
onChange={e => setNote(e.target.value)}
/>
</li>
);
}
export default function Tasks() {
const [tasks, setTasks] = useState([
{ id: 'a1', title: 'Write' },
{ id: 'b2', title: 'Test' },
]);
function addToTop() {
setTasks([{ id: crypto.randomUUID(), title: 'Plan' }, ...tasks]);
}
return (
<>
<button onClick={addToTop}>Add "Plan" to the top</button>
<ul>
{tasks.map((task, index) => (
<Row key={index} title={task.title} />
))}
</ul>
</>
);
}To reproduce the bug, type "draft" into the note field beside "Write". Then click the button. The note "draft" now sits beside "Plan". The title changed correctly, but the typed text stayed in the same position.
React did exactly what the keys told it to do. Here is the sequence.
Key 0 existed before and exists after, so React kept that instance and only changed its title prop. The state came along. Key 2 is new, so React created a fresh row for "Test", which is why that row lost any note it had.
The fix
Use the item's id. The only change is one line:
{tasks.map(task => (
<Row key={task.id} title={task.title} />
))}Now the row for "Write" keeps key a1 wherever it appears in the array. React moves that instance rather than reassigning it, and the note stays with "Write".
The same problem appears with removal and sorting. If you delete the first item from an index-keyed list, every later item shifts down one index. React then sees the last key disappear, so it destroys the last row's instance, and the state of the deleted row is inherited by its successor. Sorting causes the same mismatch for every row that moves.
Where good keys come from
| Source | Good key? | Notes |
|---|---|---|
| Database or API id | Yes | The best choice. It is already unique and permanent. |
| Id generated when the item is created | Yes | Use `crypto.randomUUID()` or a counter inside the event handler that creates the item, then store it with the item. |
| Array index | Only for static lists | See the section below. |
| Value generated during render | No | `Math.random()` gives a new key each render, so React rebuilds every row each time. |
| A text field such as `name` | Rarely | It works only if values are unique and never edited. Renaming an item would change its identity. |
The important distinction in the second row is when the id is created. Generate it once, when the data is created, and keep it in state with the rest of the item. Do not generate it in the map callback.
// Wrong: a new key on every render
{items.map(item => <li key={Math.random()}>{item.name}</li>)}
// Right: the id was created with the item and stored in state
{items.map(item => <li key={item.id}>{item.name}</li>)}With a random key in render, React treats every row as new on every render. It unmounts and remounts each one. Inputs lose focus while the user types, state resets, and the list becomes slow.
If data arrives without ids, add them once when you load or create it, not each time you render:
const withIds = rawItems.map(item => ({ ...item, id: crypto.randomUUID() }));Call this once, for example when initializing state, and not on each render. crypto.randomUUID() is available in browsers on secure contexts (HTTPS or localhost) and in current Node.js versions.
When an index is acceptable
React's own documentation allows index keys when you do not supply an explicit one, and it is a reasonable choice when all of these hold:
- The list is built once and never reordered, filtered in place, inserted into, or deleted from.
- The items have no internal state and no uncontrolled inputs.
- The items have no natural id.
A static list of navigation labels defined in your source file fits this description. If you are unsure, add an id. It costs one field and removes a class of bugs.
Gotchas
Key goes on the outermost element in the `map`
The key must be on the element the callback returns, and it must be on the component usage, not inside the component.
// Wrong: the key is inside Row, so the list's top-level elements have none
function Row({ task }) {
return <li key={task.id}>{task.title}</li>;
}
{tasks.map(task => <Row task={task} />)}
// Right
{tasks.map(task => <Row key={task.id} task={task} />)}Keys are not props
key is consumed by React. A component cannot read props.key. If a child needs the id, pass it under another name:
<Row key={task.id} id={task.id} title={task.title} />Duplicate keys
If two siblings share a key, React logs a warning, and updates can go wrong because React cannot tell the items apart. Duplicates usually come from merging two data sources whose ids overlap. Combine a type with the id to make a composite key:
{[...users, ...groups].map(entry => (
<li key={`${entry.kind}-${entry.id}`}>{entry.name}</li>
))}Keys on a different level
Keys only need to be unique among siblings. Two separate lists on the same page can each have an item with key 1. Nested lists likewise have their own key space.
Keys for multiple elements per item
When each item renders two sibling elements, use Fragment with a key, because the short <>...</> syntax cannot take one. The next chapter covers this in detail.
Keys can also be used on purpose
Because a changed key destroys and recreates the instance, you can reset a component by changing its key. This is the other side of identity: the same mechanism that makes index keys dangerous is a useful tool when you want a fresh start, such as clearing a form when the user switches records. A later chapter in this tutorial covers that pattern.
Decision checklist
- Does each item already have an id from your data source? Use it.
- Do you create items in the browser? Generate an id once, in the handler that creates the item, and store it on the item.
- Is the list static, stateless, and never reordered? An index is acceptable.
- Are you tempted to call
Math.random()inmap? Do not.
Exercise
A list of chat messages is rendered with key={index}. New messages are added at the top. Each message component has a "reply draft" input. A user types a draft under the second message, then a new message arrives. Where does the draft appear, and what change fixes it?
Show answer
The draft appears under the third message, which is the second message's old content shifted down by one. The row at index 1 keeps its instance and state, but its props now hold the new second message. The fix is to key each message by a stable id from the message data, for example key={message.id}, so the instance moves with the message.
Exercise
Why does key={Math.random()} make a list work visually but behave badly when the user types in an input inside a row?
Show answer
Each render produces new keys, so React sees every row as a new item. It unmounts all the old rows and mounts new ones. The input inside the row is recreated on each render, so it loses its state and focus after each keystroke that triggers a re-render.