How React's Key Drives List Reconciliation: A Source Code Deep Dive
This article explores how React's key prop works internally, tracing its path from JSX to ReactElement and Fiber, and detailing the three-phase reconciliation algorithm that matches old and new nodes during list updates, with source code examples from React v19.2.8.
Initial Encounter with key
When rendering a list in React, omitting a key triggers a console warning. The official docs state that key helps React match components to array items for efficient updates when items move, insert, or delete. However, they don't explain what key actually is or where it lives inside React.
key is not a regular prop
Although written on the JSX tag, key does not become a DOM attribute (the browser's Elements panel shows no key on the <li>). It also does not reach the child component as props.key; React reserves it and warns if accessed in development. If the component needs the identifier, pass it separately.
key is first stored in ReactElement
JSX compiles to jsx / jsxs calls. The third argument becomes the key of the created ReactElement. A simplified ReactElement structure:
function ReactElement(type, key, props, owner, debugStack, debugTask) { return { $$typeof: REACT_ELEMENT_TYPE, type, key, props, _owner: owner }; }React normalizes key to a string; if omitted, ReactElement.key is null (React does not write the array index into the key field). Source: https://github.com/react/react/blob/v19.2.8/packages/react/src/jsx/ReactJSXElement.js
key then flows into Fiber
ReactElementdescribes the desired UI; Fiber tracks state, update relationships, and work progress. FiberNode also has a key field, copied from the element during fiber creation:
function createFiberFromElement(element, mode, lanes) { const fiber = createFiberFromTypeAndProps(element.type, element.key, element.props, ...); return fiber; }Source: https://github.com/react/react/blob/v19.2.8/packages/react-reconciler/src/ReactFiber.js. During updates, the previous render's fiber holds the old key, while the new ReactElement carries the new key. React uses these to establish correspondence between old and new nodes, then combines element type to decide reuse.
How key Is Used in Reconciliation
Reconciliation (often called React Diff) compares the fiber tree with new descriptions to decide what to keep, update, move, insert, or delete. Key points:
React reconciles only direct children of the same parent; it does not infer arbitrary cross-level moves.
For each ReactElement, React compares key first, then element type to determine if an old fiber can be reused.
Without explicit keys, unkeyed children use their current position as the matching basis, causing state mismatches on insertions, deletions, or reordering.
Entry function: reconcileChildFibers
The diff logic lives in reconcileChildFibers (source: https://github.com/react/react/blob/v19.2.8/packages/react-reconciler/src/ReactChildFiber.js:1767), which branches into single-node and multi-node diffing. Key-based reuse happens in both.
Single-node diff
When the new child is a single ReactElement, reconcileSingleElement searches the old fiber's sibling chain:
Compare new element's key with each old fiber's key.
If keys match, compare type.
Key and type both match → reuse old fiber (create work-in-progress via useFiber).
Key matches but type differs → cannot reuse; create new fiber, mark old fiber for deletion.
Key mismatch → continue to next sibling, deleting skipped old fibers.
Multi-node diff: reconcileChildrenArray
When new children form an array, React must handle updates, insertions, deletions, and reordering. The algorithm scans left-to-right using indices for the new array and the sibling pointer for the old fiber list. It proceeds in three phases.
Phase 1: Left-to-right sequential comparison
React calls updateSlot for each pair newChildren[i] vs oldFiber:
function updateSlot(returnFiber, oldFiber, newChild, lanes) { const key = oldFiber ? oldFiber.key : null; if (isReactElement(newChild)) { if (newChild.key !== key) return null; return updateElement(returnFiber, oldFiber, newChild, lanes); } ... }If key differs, updateSlot returns null and the sequential scan stops. This only means the current position cannot match; remaining nodes may still be reusable.
If keys match, updateElement checks type:
Key and type match → reuse old fiber (via useFiber).
Key matches but type differs → create new fiber; if shouldTrackSideEffects and newFiber.alternate === null, mark old fiber for deletion via deleteChild. The scan continues.
Phase 2: Determine which side exhausted first
After the sequential scan:
New array exhausted ( newIdx === newChildren.length): remaining old fibers are deleted via deleteRemainingChildren.
Old fiber list exhausted ( oldFiber === null): remaining new children are created via createChild and marked for insertion with placeChild.
Both have leftovers : proceed to Phase 3.
Phase 3: Map-based lookup for remaining nodes
React builds a Map from the remaining old fibers using mapRemainingChildren:
function mapRemainingChildren(currentFirstChild) { const existingChildren = new Map(); let existingChild = currentFirstChild; while (existingChild) { const mapKey = existingChild.key !== null ? existingChild.key : existingChild.index; existingChildren.set(mapKey, existingChild); existingChild = existingChild.sibling; } return existingChildren; }Storage rule: explicit key → use key; no key → use fiber's index.
Then for each remaining new child, updateFromMap looks up a match:
function updateFromMap(existingChildren, returnFiber, newIdx, newChild, lanes) { if (isReactElement(newChild)) { const mapKey = newChild.key === null ? newIdx : newChild.key; const matchedFiber = existingChildren.get(mapKey) || null; return updateElement(returnFiber, matchedFiber, newChild, lanes); } return null; }Lookup rule: new child has key → use key; no key → use newIdx.
After updateElement:
Key and type match → reuse old fiber; remove it from the map.
Key matches but type differs → create new fiber.
No match → create new fiber.
After all new children are processed, any fibers left in the map are deleted.
Placement and movement: placeChild
Each new fiber passes through placeChild to decide if it needs a Placement flag (insert or move). The function uses alternate to detect reuse:
function placeChild(newFiber, lastPlacedIndex, newIndex) { newFiber.index = newIndex; if (!shouldTrackSideEffects) { newFiber.flags |= Forked; return lastPlacedIndex; } const current = newFiber.alternate; if (current) { const oldIndex = current.index; if (oldIndex < lastPlacedIndex) { newFiber.flags |= Placement; return lastPlacedIndex; } return oldIndex; } newFiber.flags |= Placement | PlacementDEV; return lastPlacedIndex; }Two key values: oldIndex: the reused node's position in the old list. lastPlacedIndex: the maximum old index among nodes already confirmed to not need moving.
Rule: oldIndex < lastPlacedIndex → node moved; mark Placement. oldIndex >= lastPlacedIndex → node keeps relative order; update lastPlacedIndex = oldIndex.
Worked example: A B C D → A C D B
Assume keys equal letters. Sequential scan matches A (oldIndex 0, lastPlacedIndex 0). Next, new C vs old B: keys differ → scan stops. Remaining old fibers B, C, D go into map. Map lookups:
C: oldIndex 2 ≥ 0 → no move, lastPlacedIndex = 2.
D: oldIndex 3 ≥ 2 → no move, lastPlacedIndex = 3.
B: oldIndex 1 < 3 → move, mark Placement.
Result: A, C, D stay; B moves.
Counter-intuitive case: A B C D → D A B C
Sequential scan: new D vs old A → keys differ, stop. Map gets A, B, C, D. Lookups:
D: oldIndex 3 → lastPlacedIndex = 3.
A: oldIndex 0 < 3 → mark Placement.
B: oldIndex 1 < 3 → mark Placement.
C: oldIndex 2 < 3 → mark Placement.
React marks A, B, C as moving, even though moving only D would be fewer operations. The forward-scan algorithm prioritizes preserving the longest increasing subsequence of old indices.
Choosing Keys in Practice
A valid key must be:
Unique among siblings : no duplicates in the same list.
Stable across renders : the same data item keeps the same key after re-renders, sorting, or moving.
Prefer backend-provided business IDs
If the backend returns a unique, stable ID per record, use it directly: <UserItem key={user.id} user={user} />. Uniqueness is only required within the sibling list.
Composite keys when IDs are only unique within a scope
If IDs repeat across tenants, groups, or data sources, combine the scope identifier with the ID: key={`${user.tenantId}:${user.id}`} Same pattern applies to order/line-item, product/variant, etc. The combined fields must jointly identify a business record and remain stable while that record's identity persists.
When index is acceptable
Array index represents position. Using index as key tells React to identify nodes by position. If the list undergoes insertions, deletions, or reordering, the same position may hold different data, but the key stays the same, causing React to reuse the wrong component (including its state). Therefore, prefer stable business identifiers for mutable lists.
For static lists with fixed content and order, index is acceptable. The deciding factor: does the mapping between a data item and its position change during updates? Lists containing inputs, animations, or component state make position-change mismatches more visible.
Summary
From JSX to ReactElement to Fiber, key consistently participates in node identity recognition. During list updates, React uses it to establish old-to-new correspondence, then combines type and position to decide reuse, deletion, insertion, or movement. The core principle when choosing a key: keep the same business data's identity stable across renders.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
