Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

React Keys and Reconciliation: How List Diffing Works and Index Key Bugs

React matches children by key, not by content. Why index keys shift state on insert, and how a key doubles as an intentional reset.

~4 min readReact
#React#Rendering#Performance
3D illustration of Fiber virtual DOM nodes matched by stable keys while a list is reordered

Quick Summary

React compares the previous element tree with the next one and applies the minimum set of DOM changes. The comparison is a heuristic, not a tree-diff algorithm: different element types mean "destroy and rebuild", the same type means "update props in place", and lists are matched by key — or by position when there is no key.

That last clause is the source of nearly every list bug. With index keys, React matches the first child to the first child no matter which item it represents, so inserting at the top shifts every state, every uncontrolled input value, and every focused DOM node by one row. With stable keys, React moves the existing elements and only mounts the new one.

A key does not enter the component as a prop. It is a hint for the reconciler, so props.key is undefined, and changing a key deliberately unmounts and remounts the element — which is why key is also the cleanest way to reset a component's state.

Basic Syntax & Signature

tsx
type Item = { id: string; label: string; done: boolean }; function TodoList({ items }: { items: Item[] }) { return ( <ul> {items.map((item) => ( // Stable identity: React tracks this row by item.id, not position. <TodoRow key={item.id} item={item} /> ))} </ul> ); } function TodoRow({ item }: { item: Item }) { // Not a prop: `item.key` would be undefined. // Uncontrolled input state is tied to the DOM node React reuses. return ( <li> <input type="checkbox" defaultChecked={item.done} /> {item.label} </li> ); } // A key on a fragment groups siblings without a wrapper element. function Pairs({ rows }: { rows: Array<{ id: string; a: string; b: string }> }) { return ( <dl> {rows.map((row) => ( <Fragment key={row.id}> <dt>{row.a}</dt> <dd>{row.b}</dd> </Fragment> ))} </dl> ); } import { Fragment } from "react";

The reset pattern:

tsx
function Profile({ userId }: { userId: string }) { // Changing the key remounts Profile for a different user: all state resets, // effects re-run, refs are re-attached. return <ProfileEditor key={userId} userId={userId} />; } function ProfileEditor({ userId }: { userId: string }) { const [draft, setDraft] = useState(""); return <input value={draft} onChange={(e) => setDraft(e.target.value)} aria-label={userId} />; }

Key Comparison Table

SituationReact doesConsequence
Different element type at the same positionUnmount old subtree, mount newState and DOM nodes are recreated
Same type, different propsUpdate props in placeState is preserved
List with stable keysMatch by key, move existing nodesState follows the item
List without keysMatch by indexState follows the position
Duplicate keysWarns, then behaves unpredictablyWrong rows reuse state
Key changesUnmount and remount that elementIntentional state reset
Key on a componentConsumed by Reactprops.key is undefined
key on a fragmentGroups multiple childrenNo extra DOM node
Key choiceInsert at topSortDelete middle
item.idCorrectCorrectCorrect
indexState shifts by oneState scramblesState shifts back
crypto.randomUUID()Remounts everything each renderSameSame
${id}-${version}Remounts that item when version changesFineFine

Practical Edge Cases & Deep Dives

1. Index keys corrupting state on insert

tsx
function IndexKeys({ rows }: { rows: string[] }) { return ( <ul> {rows.map((row, index) => ( // Broken: React reuses the node at position 0 for the new row. <li key={index}> <input defaultValue={row} /> </li> ))} </ul> ); } function IdKeys({ rows }: { rows: Array<{ id: string; text: string }> }) { return ( <ul> {rows.map((row) => ( <li key={row.id}> <input defaultValue={row.text} /> </li> ))} </ul> ); }

Prepending a row to IndexKeys leaves the DOM input values attached to the old positions, so the first input now shows the second row's text. The DOM is not "wrong" from React's perspective — it correctly updated the props of the elements it kept. Only the identity was wrong, and identity is exactly what a key supplies.

2. Sorting a table with index keys

tsx
type Row = { id: string; name: string; score: number }; function Table({ rows }: { rows: Row[] }) { const [sortAsc, setSortAsc] = useState(true); const sorted = [...rows].sort((a, b) => (sortAsc ? a.score - b.score : b.score - a.score)); return ( <> <button onClick={() => setSortAsc((v) => !v)}>sort</button> <table> <tbody> {sorted.map((row) => ( <tr key={row.id}> <td>{row.name}</td> <td>{row.score}</td> <td><RowActions row={row} /></td> </tr> ))} </tbody> </table> </> ); } function RowActions({ row }: { row: Row }) { // Local state that must follow the row, not the position. const [open, setOpen] = useState(false); return <button onClick={() => setOpen((o) => !o)}>{open ? `editing ${row.name}` : "edit"}</button>; }

With key={index}, reversing the sort order leaves each RowActions component attached to a row it no longer describes — the "editing" panel stays on row 1's position while the data under it changes. With key={row.id} the component moves with the row and the panel stays on the right record.

3. Keys and remounting for reset

tsx
function SearchPage({ query }: { query: string }) { return ( <div> {/* A new query resets the whole results subtree: no stale page number, no leftover scroll position, no old draft in the filter box. */} <Results key={query} query={query} /> </div> ); } function Results({ query }: { query: string }) { const [page, setPage] = useState(1); const [filter, setFilter] = useState(""); return ( <div> <p>{query} page {page} filter {filter || "none"}</p> <button onClick={() => setPage((p) => p + 1)}>next</button> <input value={filter} onChange={(e) => setFilter(e.target.value)} /> </div> ); }

This replaces a useEffect that watches query and resets state — one render instead of two, and no window in which the old page number is visible with the new query. The cost is a full remount of the subtree, which is exactly what "start over" means.

4. key is not a prop, and spreading breaks it

tsx
function Wrapper(props: { title: string; children?: React.ReactNode }) { // `props.key` is undefined: React removes it before rendering. return <section aria-label={props.title}>{props.children}</section>; } function App({ items }: { items: Array<{ id: string; title: string }> }) { return ( <div> {items.map((item) => { const { id, ...rest } = item; // Wrong: the key is not inside `rest`, so React cannot see it. // <Wrapper key={id} {...rest} /> // Right: pass key explicitly alongside the spread. return <Wrapper key={id} {...rest} />; })} </div> ); }

React 19 warns when a props object containing key is spread into JSX, because the reconciler may see both a spread key and an explicit key. The safe pattern is to destructure the identity out and pass key as a literal attribute, as above.

5. Duplicate keys and what they do

tsx
function Tags({ tags }: { tags: Array<{ label: string }> }) { return ( <ul> {tags.map((tag) => ( // If two tags share a label, React warns and reuses one of the nodes. <li key={tag.label}>{tag.label}</li> ))} </ul> ); }

Keys must be unique among siblings. Duplicates produce a console warning ("Encountered two children with the same key") and undefined behaviour in which one node is reused for two elements — most visible when the duplicated rows have local state or uncontrolled inputs. The fix is a stable unique id, not an index appended to the key: key={${tag.label}-${index}} hides the warning and keeps the position-dependence bug.

6. Reconciliation above and below the list

tsx
function Panel({ tab, items }: { tab: "a" | "b"; items: string[] }) { return ( <div> {/* Different type on the same position: the whole subtree remounts. */} {tab === "a" ? <ListView items={items} /> : <GridView items={items} />} {/* Same type, different props: one instance updated. */} <Summary items={items} /> {/* Same component, different key: remount on purpose. */} <Summary key={tab} items={items} /> </div> ); } function ListView({ items }: { items: string[] }) { return <ul>{items.map((i) => <li key={i}>{i}</li>)}</ul>; } function GridView({ items }: { items: string[] }) { return <div>{items.map((i) => <span key={i}>{i}</span>)}</div>; } function Summary({ items }: { items: string[] }) { return <p>{items.length} items</p>; }

Switching tab between ListView and GridView destroys one and creates the other — any state inside them is lost, even though both receive the same items. That is often desirable; when it is not, both branches should render the same component with a view prop so the instance survives.

Common Compilation/Runtime Mistakes

SymptomCauseFix
Input values shift after inserting a rowIndex keysUse a stable id
Rows show another row's expanded stateIndex keys plus reorderingkey={item.id}
Focus jumps to a different rowNode identity changedStable keys
"Encountered two children with the same key"Duplicate key valuesUnique id per item
Everything remounts every renderRandom or freshly generated keyDerive keys from data
props.key is undefinedKey is not a propPass the id separately if needed
State persists after switching recordsSame position, same keyGive the component a new key
Form does not reset on navigationComponent instance reusedkey on the form or subtree
Animation restarts on every updateElement remountedStable key, stable type
key on a fragment does nothingUsed <>...</> instead of <Fragment><Fragment key={...}>

The rule that covers all of these: a key must be derived from the identity of the data, not from its position, its content, or a random value. When no unique id exists, generate one when the item is created — crypto.randomUUID() or a counter — and store it with the item. Position is a property of the view; identity is a property of the data, and React needs the second one.

Try matching browser tools

All tools

Small utilities that fit React work — they run entirely in this browser tab, so nothing you paste leaves your device.

All React guides

More in React

All React guides

The guides filed next to this one in React, in library order.