Keys

How React knows which list item is which.

Builds on The virtual DOM and diffing.

The reconciler from chapter 5 matches children by position. For most of the tree that's exactly right: the third child of a <form> is the same thing it was last render. For lists it falls apart. Insert one item at the front and every item shifts by a position, so the diff sees every row as changed, and worse, it reuses each row's DOM node for a different item.

This chapter gives the reconciler a way to know which child is which: keys. You'll see the bug they prevent, build keyed matching into the toy, including the trick React uses to decide what to move, and then cover the other job keys do in real React, resetting state on purpose.

The problem: state sticks to positions#

Here's a shopping list on the stage 5 toy. Each row has a note field. The input has no value prop, so whatever you type lives only in the DOM node (just like focus or scroll in chapter 2). Type a note next to Milk, say "2 litres", then press Add Jam to the top.

Position matching moves your notes
<button id="add">Add Jam to the top</button>
<div id="root"></div>
Nothing logged yet.

Your note is now next to Jam. The console explains why: the toy compared new row 0 (Jam) with old row 0 (Milk), saw the same type, <li>, and kept the DOM node, patching only the text. The input inside that node, with your note in it, stayed where it was. Every row was "updated", and a new Bread row was created at the bottom.

From the reconciler's point of view nothing went wrong. It did exactly what it was told: same type at the same position means the same thing. It just doesn't know that the item at position 0 is a different item now. With a plain text list the only cost is wasted work. With anything stateful, like inputs, checkboxes, animations, or a component's own state, the state is attached to the wrong item.

Build it: keyed children#

The fix is to let each child say who it is. A key is a string that identifies an element among its siblings, stable across renders. Our createElement has stored it since chapter 3, outside the props. Now reconcileChildren uses it.

Stage 6 changes only that one function. The idea:

  1. Put the old children in a map, by key, or by position for children without a key. (A key is always a string and a position is a number, so key="0" never collides with position 0.)
  2. Walk the new children. For each one, look up its old counterpart in the map. Same type: reconcile them (keep the DOM node, patch props). No match, or a different type: create a new instance.
  3. Old children nobody claimed are removed.
  4. Fix the order: insert the new nodes and move the reused ones that are out of place.

Step 4 is the subtle part. Which nodes need to move? React uses a simple rule, tracked with one number, lastPlacedIndex: walk the new list left to right, and for each reused child look at its old index. If it's at or after the highest old index kept so far, it can stay where it is, because its relative order with the ones before it is unchanged. If it's lower, it was overtaken, so it has to move.

let lastPlacedIndex = 0;
element.props.children.forEach((childElement, index) => {
  const match = existing.get(childElement.key ?? index);
  if (match && match.child.element.type === childElement.type) {
    existing.delete(childElement.key ?? index);
    const child = reconcile(parentDom, match.child, childElement);
    // Old position earlier than one we've already kept? Then it moved.
    if (match.index < lastPlacedIndex) child.needsMove = true;
    else lastPlacedIndex = match.index;
    next.push(child);
  } else {
    const child = instantiate(childElement);
    child.isNew = true;
    next.push(child);
  }
});

Then the toy walks the new children from right to left, inserting each new or moved node right before its next sibling's node, which is always already in its final place. Here's the complete function:

toy.js (stage 6)
function reconcileChildren(instance, element) {
  const parentDom = instance.dom;
  const existing = new Map();
  instance.childInstances.forEach((child, index) => {
    existing.set(child.element.key ?? index, { child, index });
  });

  const next = [];
  let lastPlacedIndex = 0; // React's trick for deciding what has to move
  element.props.children.forEach((childElement, index) => {
    const match = existing.get(childElement.key ?? index);
    if (match && match.child.element.type === childElement.type) {
      existing.delete(childElement.key ?? index);
      const child = reconcile(parentDom, match.child, childElement);
      // Old position earlier than one we've already kept? Then it moved.
      if (match.index < lastPlacedIndex) child.needsMove = true;
      else lastPlacedIndex = match.index;
      next.push(child);
    } else {
      const child = instantiate(childElement);
      child.isNew = true;
      next.push(child);
    }
  });

  // Whatever wasn't matched is gone.
  for (const { child } of existing.values()) {
    parentDom.removeChild(child.dom);
    record("REMOVE", describe(child.element));
  }

  // Insert new nodes and move the ones that need it, right to left, so the
  // node after the current one is always already in its final place.
  let nextDom = null;
  for (let i = next.length - 1; i >= 0; i--) {
    const child = next[i];
    if (child.isNew || child.needsMove) {
      parentDom.insertBefore(child.dom, nextDom);
      record(child.isNew ? "CREATE" : "MOVE", describe(child.element));
      child.isNew = child.needsMove = false;
    }
    nextDom = child.dom;
  }
  return next;
}

Same shopping list, now with key={item.id} on each row and the stage 6 toy. Type a note next to Milk and add Jam again.

Keys keep notes with their items
<button id="add">Add Jam to the top</button>
<button id="rotate">Move the last item to the top</button>
<div id="root"></div>
Nothing logged yet.

One CREATE, and your note stays with Milk. Now try Move the last item to the top. The console shows every item except the one you moved being moved: Bread is matched first, at old index 2, so lastPlacedIndex jumps to 2, and Milk (old index 0) and Eggs (old index 1) both count as overtaken. One move would have done it. The heuristic only ever moves nodes to the right relative to their siblings, so moving the last item to the front is its worst case. It's still correct, and it's linear. Real React has exactly the same behavior, because it uses exactly the same rule.

A list update, matched by index or by key
BeforeAfterMilk [2 L]Eggs [a dozen]Bread [rye]Jam [2 L]✗Milk [a dozen]✗Eggs [rye]✗Bread [ ]new nodeDOM operations: 4UPDATE text "Milk" → "Jam"UPDATE text "Eggs" → "Milk"UPDATE text "Bread" → "Eggs"CREATE <li>Bread</li>

Matched by index: row 0 is compared with row 0, so Milk's node becomes Jam's row and keeps Milk's note. Every note is now next to the wrong item, and four operations did the work of one.

Each row is an <li> with an uncontrolled input holding a typed note. The note lives in the DOM node, so it follows whichever node React reuses. Switch between index matching and keys, and between the two updates.

The real thing: keys in React#

React's child reconciliation (reconcileChildrenArray in the source) does what stage 6 does, with one optimization in front. It first walks old and new children side by side while their keys match, which handles the common cases (nothing changed, items appended, items removed from the end) without building a map. Only when keys diverge does it put the remaining old children in a map, keyed by key or by index, and continue with lastPlacedIndex, flagging moved and new fibers with Placement for the commit phase. Unclaimed old fibers are marked for deletion.

Here's the bug in real React. The Key switch flips between key={index} and key={item.id}. With index keys, type a note next to Milk and add an item; then switch to id keys and try again.

Index keys in real React
<label><input type="checkbox" id="useId"> key = item.id (unchecked: key = index)</label>
<p><button id="add">Add Jam to the top</button></p>
<div id="root"></div>

With key={index}, keys are just positions with extra steps: key 0 is "whatever is first", so React does exactly what the stage 5 toy did, and the note moves to Jam. Switching the checkbox changes every key from a number to an id, so React treats every row as new and remounts the list, clearing the notes. From then on, notes follow their items.

When index keys are fine#

Index keys are safe when the list is static: never reordered, filtered, or inserted into (except at the end), and items have no state of their own. A fixed set of tabs or a list of plain text rendered once qualifies. When React sees a list with no keys at all, it uses the index and warns in development ("Each child in a list should have a unique key prop"). Passing key={index} silences the warning without fixing anything.

Keys only need to be unique among siblings#

A key identifies a child within one parent's list of children. Two different lists can use the same keys. It goes on the element returned from map, the outermost one, not on something inside it:

// Wrong: the key is on the <li> inside Row, not on the element in the array.
{items.map((item) => <Row item={item} />)}
function Row({ item }) {
  return <li key={item.id}>{item.name}</li>;
}

// Right: the array's elements carry the keys.
{items.map((item) => <Row key={item.id} item={item} />)}

If one item renders several siblings, use a keyed fragment: <Fragment key={item.id}>...</Fragment>. The <> shorthand can't take a key.

Keys to reset state on purpose#

Keys aren't only for lists. A key changes an element's identity anywhere, and that's a useful tool. If a component should start fresh when something changes, give it that something as a key:

<ChatDraft key={contact.id} contact={contact} />

When contact.id changes, the old ChatDraft is unmounted (its state and DOM thrown away) and a new one is mounted, so a half-written message for Alice never appears in Bob's conversation. Without the key, React would see the same type at the same position and keep the state. This is how you reset a form when switching records, without effects that copy props into state.

It's the same rule as everything in this chapter and the last: type plus key, at a position, is identity. Same identity, state is kept. Different identity, state is reset.

Pitfalls#

Check your understanding#

Fix itNotes on the wrong item

Type a note next to Milk, then press Add to top. The note jumps to the new item. Fix the list so notes stay with their items. Press Check when you think it works.

import { createRoot } from "react-dom/client";

const root = createRoot(document.getElementById("root"));
let items = [
  { id: 1, name: "Milk" },
  { id: 2, name: "Eggs" },
];
let nextId = 3;

function List({ items }) {
  return (
    <div>
      <button onClick={addToTop}>Add to top</button>
      <ul>
        {items.map((item, index) => (
          <li key={index}>
            <span>{item.name}</span> <input placeholder="note" />
          </li>
        ))}
      </ul>
    </div>
  );
}

function addToTop() {
  items = [{ id: nextId, name: `Item ${nextId++}` }, ...items];
  draw();
}

function draw() {
  root.render(<List items={items} />);
}

draw();
PredictHow many moves?

A keyed list [A, B, C, D, E] is re-rendered as [B, C, D, E, A] (first item moved to the end). Using React's lastPlacedIndex rule, which items get moved? Then: what about [E, A, B, C, D] (last item moved to the front)?

Quick checkWhen is key={index} safe?

When is using the array index as a key acceptable?

Explain it out loudWhy does React need keys?

An interviewer asks: "Why does React need keys, and what goes wrong with index keys?"

Interview angle

Say it in 30 seconds

React matches each new child to an old one when it reconciles a list. Without keys it matches by position, so inserting at the top makes every row look changed and, worse, reuses each row's DOM node and state for a different item. A key gives a child a stable identity among its siblings: React matches by key, keeps matching DOM and state, and only creates, deletes or moves what changed. Index keys are positions in disguise and break on insert, delete, filter or reorder. Changing a key on purpose remounts a component, which is how you reset its state.

Why does React need keys in lists?

basic

What's wrong with using the array index as a key?

basic

How can keys be used outside of lists?

intermediate

How does React decide which keyed children to move?

senior

What happens if you generate keys with Math.random() during render?

basic

Recap#

  • Without keys, children match by position. Inserting or reordering makes the diff rewrite every row and attach DOM and component state to the wrong item.
  • A key identifies a child among its siblings. React matches old and new children by key, keeps what matches, creates what's new, deletes what's gone and moves what's out of order.
  • React decides moves with lastPlacedIndex: a reused child whose old index is lower than the highest kept so far moves. Linear and correct, but moving the last item to the front moves everything else.
  • Index keys are positions in disguise. Fine for static lists; wrong as soon as items are inserted, removed, filtered or reordered. Never use random keys.
  • Type plus key at a position is identity. Changing a key is the clean way to reset a component's state.

Sources#