Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 3.3 — Keys: How React Tells Items Apart
React · Example 2 of 4

The same bug with useState: stars move when you reorder

Asha got one star in both lists, then the order was reversed. With index keys the star stayed in the first row, which is now Meera. With id keys it moved with Asha. State belongs to the key, not to the data you pass in.

A key is a label you give each item in a list so React can match it with the same item on the next render; keys must be unique among siblings and stable, which is why they come from your data's ids and not from the index or Math.random().

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Fix this list so it has no warning and no state bug: todos.map((t, i) => <TodoRow key={i} todo={t} />), where each todo is { id, text }.

02

Write a NewTodo handler that adds { text } typed by the user to a todos state array with a proper key, and the matching map.

03

Render a table body from rows = [{ id, name, score }] where each item becomes two <tr> elements: one with the name and one with the score. Key it correctly.

Explain it without notes

01

What is a key in React, and why does React need one for list items?

02

What are the rules for a good key? Where should keys come from?

03

Why is using the array index as a key a problem? When is it acceptable?

04

What goes wrong with key={Math.random()}?

05

How do you key an item that renders several sibling elements without a wrapper?

The same bug with useState: stars move when you reorder

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

key = index: Meera ★ 1, Ravi ★ 0, Asha ★ 0
key = id:    Meera ★ 0, Ravi ★ 0, Asha ★ 1