Catalog My learning Blog
Frontend Developer Course: 100 Concepts in 100 Days · Phase 6 · Lesson 55 · 5 min read

React Keys and Reconciliation: Why Index Keys Break

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: The Index Key Bug and Its Fix
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Explain how a framework reconciles a new element tree with the previous one, why list items need stable unique keys, what goes wrong with array indexes or random keys, and how keys can be used deliberately to preserve or reset component state.

Concept Explanation

After every render, React has a new tree of elements and must update the DOM to match it. Comparing two arbitrary trees optimally is expensive, so React uses a fast heuristic called reconciliation. It compares elements at the same position: if the type is the same, a div with a div or the same component with the same component, it keeps the existing DOM node or component instance, with its state, and updates only the changed attributes and props. If the type differs, it tears down the old subtree, losing its state and DOM, and builds a new one. This makes updates linear in the size of the tree.

Lists break the position-based approach. When an item is inserted at the start of a list, every item shifts one position, and comparing by position would make React think every item changed. Keys solve this. A key is a stable identifier you give each item in a list, usually the record's id from the database. React matches old and new children by key instead of position, so it can see that one item was inserted and the others merely moved, preserving their DOM nodes and component state.

Choosing keys correctly matters. Keys must be unique among siblings and stable across renders. Database ids, slugs or other natural identifiers are ideal. Array indexes are only safe when the list is static, never reordered, filtered or inserted into, because the index of a given item changes when the list changes. With index keys, state follows positions instead of items: type into the input of the third row, delete the first row, and your text appears in what is now the third row, a different item. Random keys generated during render, such as Math.random() or a new UUID, are worse: every render produces new keys, so React destroys and recreates every item, losing focus, state and performance.

Keys are not only for lists. Because a different key means a different component identity, changing the key of a component is a deliberate way to reset its state. Day 54 used key={userId} so a profile form resets when the user changes. The opposite case also matters: rendering the same component in a different position, such as inside a conditional wrapper on one branch and outside it on another, changes its position in the tree and resets its state unexpectedly. Keeping the tree structure stable preserves state.

Other frameworks face the same problem with the same solution: Vue uses the key attribute in v-for, Angular's control flow requires a track expression in @for, Svelte uses keyed each blocks and Solid's For component tracks items by reference. The lesson transfers everywhere: identity in a dynamic list must come from the data, not from its position.

Key choiceBehaviorVerdict
Database id or slugStable, unique, follows the itemCorrect
Array index, static listPositions never changeAcceptable
Array index, dynamic listState follows positions, not itemsBug
Math.random() or new UUID per renderEverything remounts each renderBug and slow
Composite key such as user and dateUnique when no single id existsCorrect if stable
Changing key on purposeComponent remounts with fresh stateReset technique

Worked Example: The Index Key Bug and Its Fix

Each row has an uncontrolled input that holds local state. With index keys, deleting a row moves typed text to the wrong item.

TypeScript
function GuestList() {
  const [guests, setGuests] = useState([
    { id: 'g1', name: 'Ana' },
    { id: 'g2', name: 'Ben' },
    { id: 'g3', name: 'Chen' },
  ]);
  const remove = (id) => setGuests((gs) => gs.filter((g) => g.id !== id));

  return (
    <>
      <h3>Broken: index keys</h3>
      <ul>
        {guests.map((g, i) => (
          <li key={i}>
            {g.name} <input placeholder="Dietary note" />            {/* state belongs to position i */}
            <button onClick={() => remove(g.id)}>Remove</button>
          </li>
        ))}
      </ul>

      <h3>Correct: stable id keys</h3>
      <ul>
        {guests.map((g) => (
          <li key={g.id}>
            {g.name} <input placeholder="Dietary note" />            {/* state belongs to the guest */}
            <button onClick={() => remove(g.id)}>Remove</button>
          </li>
        ))}
      </ul>
    </>
  );
}

// Creating items: generate the id once, when the data is created, never during render
function addGuest(name) {
  setGuests((gs) => [...gs, { id: crypto.randomUUID(), name }]);
}

// Resetting state deliberately with a key
function Editor({ documentId }) {
  return <DraftEditor key={documentId} documentId={documentId} />;
}

Type "vegetarian" next to Ana in both lists and remove Ana. In the index-keyed list, "vegetarian" now appears next to Ben, because Ben moved into position 0 and inherited that position's input state. In the id-keyed list, the note disappears with Ana as it should.

After removing Ana from a list keyed by index, Ben takes key 0 and inherits the input state that belonged to Ana. With stable id keys, React matches items by identity, removes Ana's row and keeps every other row's state.
After removing Ana from a list keyed by index, Ben takes key 0 and inherits the input state that belonged to Ana. With stable id keys, React matches items by identity, removes Ana's row and keeps every other row's state.

Real-World Examples

  • React logs a warning in development when list children lack keys, and its documentation on rendering lists explains with a similar example why indexes cause subtle bugs when items are inserted, deleted or reordered.
  • Angular 17 introduced built-in control flow in which the @for block requires a track expression, making stable identity mandatory rather than optional, a decision the Angular team explained as preventing the performance and state bugs caused by untracked lists.
Key TakeawaysReconciliation compares trees by position and type, preserving state where the type matches and recreating subtrees where it changes. In dynamic lists, keys provide identity, so use stable unique ids from the data, never indexes for changing lists or random values generated during render. Change a key deliberately to reset a component, and keep tree structure stable to preserve state.

Review Questions & Answers

It keeps the existing DOM node or component instance, including its state, and updates only the attributes or props that changed. If the type differs, it unmounts the old subtree and mounts a new one, discarding its state.

An index identifies a position, not an item. When items are inserted, removed or reordered, a given item gets a different index, so React matches it with another item's previous state and DOM, and local state such as input text or focus ends up attached to the wrong item.

Every render produces new keys, so React sees every item as new, unmounts all existing items and mounts new ones. That loses all local state and focus and makes every update expensive.

Give the component a key derived from the data it represents, such as key={userId}. When the key changes, React treats it as a different component, unmounts the old instance and mounts a fresh one with initial state.