When a list changes, React has to work out which old item is which new item. Was one removed? Did two swap places? It matches them by key. A key is a string or number that's unique among the siblings and stays the same for the same item, like a database id.
Watch keys at work
Each TaskRow has its own state: whether it's starred. Star Read the
lesson, then press Remove first:
export default function TaskRow({ title }) {
const [starred, setStarred] = useState(false);
return (
<li>
<button onClick={() => setStarred(!starred)} aria-label={`Star ${title}`}>
{starred ? "★" : "☆"}
</button>{" "}
{title}
</li>
);
}npm install and npm run dev. The starred task is removed, and the other two keep their own stars, because each row's state follows its key:
<ul>
{tasks.map((task, index) => (
<TaskRow key={task.id} title={task.title} />
))}
</ul>Index keys
Press Start again. Then, in App.jsx, change key={task.id} to
key={index}. index is the second argument map passes, the item's position:
0, 1, 2.
Run, star Read the lesson, and press Remove first. Predict what you'll see before you click.
Check your prediction
Change the lab is now starred, although you never starred it. Before the
removal, the starred row had key 0. After it, Change the lab is first, so
it now has key 0, and React gives it the state that belonged to key 0.
Use the index as a key only for a list that never changes: no reordering, adding or removing. If the rows hold nothing of their own, an index key can look fine even after a removal, which is why it's easy to miss. Once rows keep state, as this star does, they get the wrong item's state. When the data has ids, use them.
No keys at all
Delete the key prop entirely and run. The console shows React's warning:
Each child in a list should have a unique "key" prop. Without keys, React
falls back to positions, the same problem as index keys, and warns you so you
don't do it by accident.
Put key={task.id} back before moving on.
Rules for keys
- Unique among siblings. Two lists on a page can use the same ids.
- Stable. Don't generate keys while rendering, as in
key={Math.random()}. A new key every render makes React throw away and rebuild every row, losing its state. - On the element
mapreturns, here<TaskRow key=...>, not insideTaskRow. - A component can't read its own key. If it needs the id, pass it as a separate prop too.
Spot the problem
Each of these is in a list that can be reordered. Which key is fine, and what goes wrong with the others?
key={book.isbn}key={index}key={Math.random()}key={book.title}in a list where two books can have the same title
Hint 1: the idea
A key identifies an item, not its current position or the time it rendered. Check identity and uniqueness separately.
Hint 2: a first step
Is it unique among the items? Is it the same for the same item on every render?
Show one solution
- Fine. An ISBN identifies the book and doesn't change.
- Breaks when the order changes. State follows positions, not items, as you saw in the lab.
- Breaks on every render. Every row gets a new key each time, so React rebuilds them all and their state resets.
- Breaks with duplicates. Two items with the same key confuse React, and it warns: Encountered two children with the same key.
Completion is saved in this browser only. It does not measure mastery.