ReactEasy

Why are keys important?

Keys let React match list items between renders. With correct keys, React moves, inserts and removes DOM nodes and keeps each item's state attached to the right item. With missing or unstable keys, React may reuse the wrong nodes, causing lost input, wrong checkbox states, broken animations and wasted re-renders.

What goes wrong with index keys

If you prepend an item to a list keyed by index, every item's key shifts by one. React thinks item 0 changed its content rather than a new item appearing, so:

  • Internal state (input text, focus, checked state) stays with the position, not the data.
  • All items re-render and their DOM is patched instead of one node being inserted.

What goes wrong with random keys

Generating keys during render (Math.random()) makes every item new on every render: React unmounts and remounts all of them, destroying state and hurting performance.

Correct approach

  • Use stable IDs from the data.
  • If data has no IDs, generate them once when the data is loaded or created.
  • Index keys are acceptable only when the list is static: never reordered, filtered or inserted into.

Bonus: keys reset state

Because a new key means a new component instance, <Editor key={documentId} /> resets the editor when the document changes, without manual effects.

Code example

tsx
1import { useState } from "react";
2
3function Row({ label }: { label: string }) {
4 return (
5 <li>
6 {label} <input placeholder="type a note" />
7 </li>
8 );
9}
10
11export function KeyDemo() {
12 const [items, setItems] = useState([
13 { id: "x", label: "Apples" },
14 { id: "y", label: "Bananas" },
15 ]);
16
17 const prepend = () => setItems((i) => [{ id: crypto.randomUUID(), label: "Cherries" }, ...i]);
18
19 return (
20 <div>
21 <button onClick={prepend}>Prepend</button>
22 {/* Bug: type in "Apples", prepend, and the note moves to "Cherries" */}
23 <ul>{items.map((it, index) => <Row key={index} label={it.label} />)}</ul>
24 {/* Correct: notes stay with their item */}
25 <ul>{items.map((it) => <Row key={it.id} label={it.label} />)}</ul>
26 </div>
27 );
28}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app