Keys and reconciliation
You type into a row, add an item at the top, and your text is now next to the wrong item. Here is how React matches the old tree to the new one, step by step, and why key={index} sends state to the wrong row.
01 Typed text that jumps to the wrong row
A shopping list with a quantity box on each row. Type 6 next to Eggs, then click the button that adds Milk at the top.
The 6 stayed in the first row while Eggs moved down. Nothing in this code moves the input. To see why it stays put, you need to know how React decides which old row each new element is.
02 Two rules that make diffing cheap
After a render, React has the tree it built last time and a fresh tree of elements. It has to work out the smallest set of DOM changes between them. A perfect tree diff is far too slow (the general algorithms are around O(n³)), so React uses two rules and a hint, and the whole comparison is one pass, O(n).
| Old | New | React does |
|---|---|---|
| div | div (new props) | Keeps the DOM node and component state; updates the changed props |
| div | section | Different type: unmounts the whole old subtree, state and all, and builds a new one |
| Counter | Counter | Same component: keeps its state and renders it with the new props |
| list of children | list of children | Pairs them up by key; with no keys, by position |
The hint is the key. Among siblings, a key says “this element is the same item as the old one with this key”, wherever it now sits. Leave keys out of a list and React uses the position, exactly as if you had written key={index}, and logs a warning in development.
03 Index keys, drawn
Here is the click from the first section. The left panel is what React has from the last render, the middle is what List just returned, and the right is the DOM work React will commit.
- element being matched
- old row it is matched to
- old row reused
- just added
- not matched yet
Before the click, two rows are on screen, keyed by index. You have typed 6 into the input in the Eggs row. That 6 lives in the DOM input, not in React state.
React did exactly what the keys said. Key 0 was Eggs and is now Milk, so as far as React knows, the first row changed its text. The input, its typed value, its focus and any state in a child component stay with key 0.
04 Stable keys, drawn
Now the same click with key={item.id}. The internal steps follow React’s child reconciler (reconcileChildrenArray in React 18 and 19); the details may change between versions, but the result does not.
- element being matched
- old row compared
- old row reused
- just added
- taken from the map
- not matched yet
The same list, now keyed by item.id. Eggs has key e and holds your typed 6; Bread has key b. The render returned m, e, b.
{items.map((item, i) => (<li key={i}>{item.text} <input /></li>))}
{items.map((item) => (<li key={item.id}>{item.text} <input /></li>))}
An index key is only safe when the list never reorders, never has items inserted or removed except at the end, and its rows keep no state of their own. Most lists break at least one of those.
05 Using a key to reset state
Because a new key means a new component, you can change a key on purpose to throw state away. A profile form that should start clean for each user does not need an effect that clears every field:
The flip side is the type rule. Wrapping a component in a different parent element, or swapping <div> for <section> around it, also unmounts it, and its state is lost the same way.
key={Math.random()} or key={crypto.randomUUID()} in the render gives every row a new key on every render. React unmounts and rebuilds the whole list each time: inputs lose focus and typed text, and effects run their cleanup and setup again.
06 Watch it happen
Give each row a component that logs when it mounts and unmounts. Then add an item at the top with each kind of key.
With index keys the effect logs Bread because the row at key 2 is the only one React created, even though you added Milk. In development with Strict Mode, React may also log an extra unmount and mount the first time a row mounts; that is a deliberate check, not a second row.
07 When keys go wrong
<li key={i}> /* sortable table */Index keys on a list that reordersSorting, filtering or inserting gives the same key to a different item. State, focus and typed text stay with the position, not the item.<li key={item.name}> /* two "Milk" rows */Keys that are not uniqueReact warns about duplicate keys and may drop or duplicate rows. A key must be unique among its siblings; use an ID, not a display value.<li key={Math.random()}>Keys that change every renderEvery row is unmounted and rebuilt on every render, which is slow and loses all row state.<Row key={item.id} /> inside <div key={i}>The key on the wrong elementOnly the element returned directly by map needs the key. A key deeper inside does nothing for the list; React still matches the outer elements by index.move the last item to the frontMoving one item can move manyReact keeps rows that are already in increasing order and moves the rest. Moving the last of 4 items to the front marks the other 3 as moved, so very long lists that do this often can be slow.