learn deep. ship safe.Practice testsFollow ByteMunSubscribe

Concept

Reconciliation and keys

How React compares the old and new tree, and why list items need stable keys.

Reconciliation and keys explained

Reconciliation is how React works out what changed between two renders and updates only that part of the page. It compares the new element tree with the previous one: elements of the same type at the same position are updated in place, elements of a different type are thrown away and rebuilt, and items in lists are matched by their key.

The rules React follows

  • Different type, new subtree: if a <div> becomes a <section>, or <Profile> becomes <Settings>, React unmounts the old one (losing its state) and mounts the new one.
  • Same type, update in place: React keeps the DOM node or component instance and updates only the attributes and props that changed.
  • Lists use keys: a stable, unique key per item lets React match items across renders even if they move.
// Good: a stable id from the data
{todos.map((t) => <TodoRow key={t.id} todo={t} />)}

// Risky: the index changes when items are inserted, removed or reordered
{todos.map((t, i) => <TodoRow key={i} todo={t} />)}

Why keys matter

With index keys, inserting an item at the top shifts every key, so React reuses the wrong component for each row. Input text, focus and other local state end up attached to the wrong item. Index keys are only safe for lists that never reorder, insert or delete.

Using keys on purpose

Changing a component's key forces React to treat it as new, which is a clean way to reset its state, for example <Form key={userId} /> when switching users.

Common mistakes

  • Using array indexes or random values (Math.random()) as keys.
  • Defining a component inside another component's body, which creates a new type every render and remounts it each time.
  • Conditionally swapping element types that should keep their state.

What interviewers ask about reconciliation

  • "Why do lists need keys?" So React can match items between renders.
  • "Why not use the index?" State attaches to the wrong item when the list changes.
  • "How do you reset a component's state?" Give it a new key.
Concept map
Learn firstRendering
Part of ReactReconciliation and keys

What should you learn before Reconciliation and keys?

  1. PropsInputs passed from a parent component to a child.
  2. StateData that changes over time and makes the UI re-render, and where to keep it.
  3. RenderingWhen and why components render, and what triggers a re-render.

Connections to other concepts

Part of
React

Practise Reconciliation and keys

All topics