Sub topic 4
Why every list item needs a key
This chapter assumes you know JavaScript arrays and map, React function components and props, and the useState hook. You have already rendered a list with map. Now you will see what the key prop does and what goes wrong without it.
The warning you have probably seen
Render a list without keys and React prints a console warning: Each child in a list should have a unique "key" prop. The list still appears on screen, so the warning is easy to ignore. It points to a real problem that shows up as soon as the list changes.
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>
);
}The key goes on the outermost element that map returns. Here that is the li.
What a key does
A key is a label that tells React which item is which. When a component renders again, React compares the new list of elements with the previous one. Keys let it match each new element to its old counterpart, even if the item moved to a different position.
With a key, React can:
- Keep the existing DOM node and component state for an item that moved.
- Create a new node only for an item that was added.
- Remove only the node for an item that was deleted.
Without keys, React falls back to matching by position. The first old element is matched to the first new element, the second to the second, and so on.
Seeing the problem
Positional matching causes trouble when items hold state that React cannot see in your data. A text input is the classic case, because the browser keeps what the user typed.
import { useState } from 'react';
function Row({ label }) {
return (
<li>
{label} <input />
</li>
);
}
function Demo() {
const [names, setNames] = useState(['Ada', 'Grace', 'Linus']);
return (
<>
<button onClick={() => setNames(names.slice(1))}>
Remove first
</button>
<ul>
{names.map(name => (
<Row key={name} label={name} />
))}
</ul>
</>
);
}Type something into the input beside Grace, then click the button. Because each row has a key, Ada's row is removed and Grace's row keeps its text. If you delete key={name} and use an index as the key, the first row is reused for Grace, so the text typed beside Ada is now beside Grace. The last row is the one removed. The labels look right, but the state belongs to the wrong person.
Rules for keys
- Keys must be unique among siblings. Two different lists in the same parent can reuse the same values.
- Keys must not change between renders. Do not generate them with
Math.random()while rendering, because every render would give every item a new identity, and React would recreate all the nodes. - The key is not passed to your component as a prop. If the component needs the value, pass it again under another name, such as
id.
Common mistakes
| Mistake | Result |
|---|---|
| Putting the key on an inner element instead of the outer one returned by `map` | The warning stays, because React reads the key from the returned element. |
| Using `Math.random()` for keys | All items are recreated on every render, and state and focus are lost. |
| Duplicate keys among siblings | Warnings, and items may be duplicated or skipped when the list updates. |
The next chapter covers how to choose good keys, and why an array index is usually the wrong choice.
Exercise
A list of rows uses key={index}. Each row contains an uncontrolled text input. The user types in the second row, then the first item is removed from the data. Where does the typed text appear, and why?
Show answer
The text appears in what is now the first row. With index keys, React matches by position. The old second row (key 1) is matched to the new item at index 1, and the row with key 0 is reused for the new first item. Wait: the removal shifts data up, so index 0 now holds the old second item, but the DOM input at key 0 keeps its empty text, while the input at key 1 keeps the typed text and now sits beside the old third item. So the typed text stays in the second row and now belongs to a different item than the one it was typed beside. A stable id key would have moved the text with its item.