The browser and React · Question 11 of 50

How does React decide what to re-render? Why do list items need keys?

What they're checking

Reconciliation, and a real class of bugs.

The answer

When state changes, React calls the component again to get a new element tree, compares it with the previous one (reconciliation) and changes only the DOM that differs. An element of a different type is replaced; the same type is updated in place.

In lists, React matches old and new children by key. With stable keys such as an id, a moved or inserted item keeps its DOM and state. With the array index as the key, inserting at the top shifts every key, so React updates every row, and state such as an input's text can end up on the wrong row.

// fragile: the index as the key
{todos.map((t, i) => <Todo key={i} todo={t} />)}
// stable
{todos.map((t) => <Todo key={t.id} todo={t} />)}

The picture

before        key        after inserting at the top
[Buy milk]     0  ────▶  [Call mom]   0   React thinks row 0 changed
[Pay rent]     1  ────▶  [Buy milk]   1   ...and row 1
                         [Pay rent]   2   ...and adds row 2
key = id: only [Call mom] is new; the others move with their state
The follow-up they'll ask

Is a re-render the same as a DOM update?

Show the answer

No. A re-render is React calling the component; the DOM changes only where the result is different.

Your progress stays on this device.