Skip to content

Keys and reconciliation

Deep diveUnder the hood

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.

List.jsx
import { useState } from 'react';
export default function List() {
const [items, setItems] = useState([
{ id: 'e', text: 'Eggs' },
{ id: 'b', text: 'Bread' },
]);
const addMilk = () => setItems([{ id: 'm', text: 'Milk' }, ...items]);
return (
<>
<button onClick={addMilk}>Add Milk at the top</button>
<ul>
{items.map((item, i) => (
<li key={i}>
{item.text} <input placeholder="qty" />
Text
Before: After the click:
Eggs [6] Milk [6]
Bread [ ] Eggs [ ]
Bread [ ]

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).

How React matches an element at the same place in the tree
OldNewReact does
divdiv (new props)Keeps the DOM node and component state; updates the changed props
divsectionDifferent type: unmounts the whole old subtree, state and all, and builds a new one
CounterCounterSame component: keeps its state and renders it with the new props
list of childrenlist of childrenPairs 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.

key={index}: prepending Milk
Step 1 of 5
old rows (key: text, typed)
0: Eggs ✎6
1: Bread
new elements from render (key: text)
0: Milk
1: Eggs
2: Bread
work for the commit
Empty
  • 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.

key={item.id}: prepending Milk
Step 1 of 7
old rows (key: text, typed)
e: Eggs ✎6
b: Bread
new elements from render (key: text)
m: Milk
e: Eggs
b: Bread
old rows by key
Empty
work for the commit
Empty
  • 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.

Breaks on insert
{items.map((item, i) => (
<li key={i}>
{item.text} <input />
</li>
))}
Follows the item
{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:

JavaScript
// Switching userId unmounts the old form and mounts a fresh one,
// so every useState inside starts from its initial value again.
<EditProfile key={userId} userId={userId} />

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.

Row.jsx
import { useEffect } from 'react';
export function Row({ text }) {
useEffect(() => {
console.log('mount', text);
return () => console.log('unmount', text);
}, []);
return <li>{text} <input placeholder="qty" /></li>;
}
// In List, try each:
// items.map((item, i) => <Row key={i} text={item.text} />)
// items.map((item) => <Row key={item.id} text={item.text} />)
Text
key={i}, after adding Milk:
mount Bread ← the only new row is the last one
key={item.id}, after adding Milk:
mount Milk ← the new row is the one you added

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.

08 Check yourself

Question

A list uses key={i}. You delete the first row. Which old row does React remove from the DOM?

Question

You change <div className="card"><Timer /></div> to <section className="card"><Timer /></section>. What happens to Timer’s state?

Question

Two sibling lists on one page each have an item with key 42. Is that a problem?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?