Sub topic 8
Keys and Stable Identity in Lists
This chapter assumes you know JavaScript arrays and map, can write basic React components with props and JSX, and have used useState. It also builds on the previous chapter, where you saw that React decides whether to keep or reset state by comparing element type and position. Keys extend that rule to lists.
Why lists need identity
When a component returns a list, React must match each element in the new list to an element in the previous list. Without extra information, the only clue is position: the first child matches the first child, the second matches the second, and so on.
Position works while a list only grows or shrinks at the end. It breaks as soon as you insert at the front, remove from the middle, sort, or filter. The item that used to be at index 2 may now be a different item, but React would treat it as the same instance and keep its state.
A key is a string or number you attach to each element in an array. It tells React which item is which, independent of where the item sits. During reconciliation, React matches children by key first and falls back to index only when no key exists.
The basic rule
Give every element produced by map a key taken from the data, and make that key unique among siblings.
function TodoList({ todos }) {
return (
<ul>
{todos.map(todo => (
<TodoItem key={todo.id} todo={todo} />
))}
</ul>
);
}Several details are worth knowing:
- The key goes on the outermost element returned inside
map, not on an element insideTodoItem. - Keys only need to be unique among siblings. Two different lists can reuse the same keys.
keyis not passed as a prop. IfTodoItemreadsprops.key, it getsundefined. Pass the value again under another name if the component needs it.- A fragment in a list needs the explicit form
<Fragment key={id}>, because the short<>syntax cannot take a key.
What goes wrong without keys
If you omit keys, React logs a warning and falls back to using the index as the key. The fallback is silent in effect: the list renders, and the bugs appear only when the list changes.
Consider a list of inputs, each holding its own typed text in state.
import { useState } from 'react';
function NameInput({ label }) {
const [text, setText] = useState('');
return (
<li>
{label}: <input value={text} onChange={e => setText(e.target.value)} />
</li>
);
}
function Names() {
const [names, setNames] = useState(['Ada', 'Grace', 'Linus']);
function addFirst() {
setNames(['Margaret', ...names]);
}
return (
<>
<button onClick={addFirst}>Add to the front</button>
<ul>
{names.map((name, index) => (
<NameInput key={index} label={name} />
))}
</ul>
</>
);
}Type "hello" into the input labeled Ada, then click the button. The labels shift down by one, but the text "hello" stays in the first input, which is now labeled Margaret. React matched by index: the instance at key 0 still exists, so it keeps its state and receives a new label prop. The new item at key 3 is the one that gets created.
Replace key={index} with key={name} (names are unique here) and the typed text follows Ada down the list, as you would expect.
How React uses keys during reconciliation
For each parent that returns an array of children, React builds a lookup from key to previous child. For every element in the new array it then does one of three things:
- If a previous child has the same key (and the same type), React reuses that instance. Its state is kept, and it re-renders with the new props.
- If no previous child has that key, React creates a new instance with fresh state.
- If a previous key does not appear in the new array, React unmounts that instance and discards its state.
Reordering is the interesting case. When keys match but positions differ, React reuses the instances and moves their DOM nodes instead of destroying and recreating them. That preserves state, focus, scroll position inside the node, and any running animation or media playback.
A key match also requires the same element type. If key="a" was a <Row> and is now a <Card>, React unmounts the Row and mounts a Card, even though the key is equal.
Choosing a good key
A good key is stable, unique among siblings, and tied to the identity of the data rather than its position.
| Source | Verdict | Notes |
|---|---|---|
| Database id or other id from the data | Best | Stable across reloads, reorders, and filters. |
| ID generated once when the item is created, such as `crypto.randomUUID()` | Good | Generate it when you create the item and store it with the item. |
| Unique natural value, such as an email or slug | Acceptable | Only if it is truly unique and never edited while the item is shown. |
| Array index | Only for static lists | Safe if the list never reorders, inserts, or filters, and items hold no state. |
| `Math.random()` or a new UUID during render | Never | The key changes every render, so every item is unmounted and remounted. |
The last row is a common mistake:
// Wrong: a new key on every render destroys and recreates every row.
{todos.map(todo => (
<TodoItem key={crypto.randomUUID()} todo={todo} />
))}Each render, no previous key matches, so React throws away all instances. State is lost, inputs lose focus, and performance drops. If your data has no id, attach one when the data enters your app, not when it renders.
function addTodo(title) {
setTodos(todos => [...todos, { id: crypto.randomUUID(), title }]);
}Also avoid building keys from values the user can edit. If the key is the item's title and the user edits the title, the key changes and the component remounts, which can drop focus in the middle of typing.
Index keys are not always wrong
Using the index is acceptable when all of these hold: the list is static, items are never reordered or filtered, and the items hold no state or uncontrolled DOM state. A fixed list of navigation links built from a constant array is a typical case. When in doubt, use a data id.
Keys outside of lists: resetting state
Keys are not limited to arrays. Any element can have one, and changing the key tells React that this is a different component. React unmounts the old instance and mounts a new one with fresh state.
function Profile({ userId }) {
// Same component type at the same position: state would be kept
// when userId changes. Changing the key forces a fresh instance.
return <EditForm key={userId} userId={userId} />;
}Without the key, switching from user 1 to user 2 would keep whatever the user had typed into EditForm, because type and position are unchanged. With the key, the form starts clean. This is the supported way to reset state when an identifying prop changes. It is usually simpler and less error-prone than writing an effect that clears each piece of state by hand.
Common errors
- Missing key warning. The
mapcallback returns an element with nokey. Add one from the data. - Key on the wrong element. If
mapreturns<div><Item key={id} /></div>, the key must go on thediv, because that is the element in the array. - Duplicate keys. Two siblings with the same key cause React to warn, and updates can duplicate or drop items. Check that your ids are unique, especially after merging data from two sources.
- Keys that change between renders. Random values, or values computed from the index after sorting, defeat identity.
- Stale state after reordering. If state seems attached to the wrong row after a sort or insert, you are probably keying by index.
- Reading
props.key. It is alwaysundefined. Pass a separate prop.
Keys and performance
Stable keys also make updates cheaper. When items are reordered, React moves existing DOM nodes instead of rebuilding them. Keys do not by themselves stop children from re-rendering, though. A keyed child still re-renders when its parent does unless you wrap it in memo, which a later chapter covers. Keys decide identity. Memoization decides whether to skip work.
Exercise
A list of <Row> components uses key={index}. Each Row has a checkbox with its own useState for the checked value. The user checks the second row, then sorts the list alphabetically. Why might the checkmark appear on a different item, and what is the fix?
Show answer
With index keys, React matches instances by position. After sorting, the instance at index 1 still exists and keeps its checked state, but it now receives a different item's props, so the checkmark appears beside whichever item moved into slot 1. The fix is to key each Row by a stable id from the data, such as key={item.id}, so state moves with the item.
Exercise
A <Chat key={roomId} roomId={roomId} /> component holds a draft message in state. What happens to the draft when roomId changes, and what would happen if you removed the key?
Show answer
With the key, changing roomId unmounts the old Chat and mounts a new one, so the draft state is reset. Without the key, the type and position are the same, so React keeps the instance and its state, and the old draft would remain in the new room unless you clear it yourself.