Rendering twice
Keyed diff
Lesson 5 of 248 min
In this lesson
Take a list of four items, A, B, C, D, each with a key, and move the last one to the front. One DOM operation would be enough: take D and put it first. React does three. Move A from the front to the back instead, and React does one.
The function that makes this decision is short, and once you have written it the asymmetry is easy to see. In this lesson I write it: about a hundred lines, no DOM, no rendering. The input is a list of old fibers and a list of new elements. The output is a list of new fibers with notes on them.
Elements in, notes out
The input is elements, the plain objects from the Elements & JSX lesson:
$$typeof, a type, a key, and props with the children inside. The diff reads
only type, key and props.
export const REACT_ELEMENT_TYPE = Symbol.for('mini-react.element');
export type Key = string | null;
export interface ReactElement<P = any> {
$$typeof: symbol;
type: any;
key: Key;
props: P;
}The output is fibers: the class from the Fiber tree lesson, with four new fields for the diff to write its notes in.
export const Placement = /* */ 1 << 1; // insert (or move) the DOM node
export const ChildDeletion = /* */ 1 << 4; // some children must be removed (see fiber.deletions)
export class Fiber {
// … tag, key, type, return, child, sibling, pendingProps: as in the Fiber tree lesson
index = 0; // position among its siblings
flags = NoFlags; // what the commit has to do with this fiber
deletions: Fiber[] | null = null; // old children to remove during commit
alternate: Fiber | null = null; // the old fiber this one was made from; null = brand new
}Here are those notes after one diff, on a real example:
flags is one number, one bit per note
ChildDeletiongoes on the parent, next to itsdeletionslist.Placementmeans “put this node at its position in the DOM”. It covers both inserting and moving: there is no “move” flag.
ul the parent
- flags
- ChildDeletion
- deletions
- [B]
C stays
- index
- 0
- alternate
- old C, at 2
- flags
- NoFlags
A moved
- index
- 1
- alternate
- old A, at 0
- flags
- Placement
X new
- index
- 2
- alternate
- null: brand new
- flags
- Placement
B deleted
not in the new list: only the parent points at it
The full src/fiber.ts
import type { Key, ReactElement } from './shared.ts';
// Work tags: "what kind of fiber is this?" (same numbers as real React)
export const FunctionComponent = 0;
export const HostComponent = 5; // a DOM element: 'div', 'button', ...
export type WorkTag = number;
// Flags: "what the commit has to do with this fiber" (same bits as real React)
export const NoFlags = /* */ 0;
export const Placement = /* */ 1 << 1; // insert (or move) the DOM node
export const ChildDeletion = /* */ 1 << 4; // some children must be removed (see fiber.deletions)
export class Fiber {
// --- identity ---
tag: WorkTag;
key: Key;
/** The function for a component, the tag name ('div') for a host component. */
type: any = null;
/** The real thing this fiber stands for (later: the DOM node). Unused for now. */
stateNode: any = null;
// --- tree ---
return: Fiber | null = null;
child: Fiber | null = null;
sibling: Fiber | null = null;
/** Position among its siblings. */
index = 0;
// --- inputs ---
/** Props for the render that is about to happen. */
pendingProps: any;
// --- effects ---
flags = NoFlags;
/** Old children to remove during commit. */
deletions: Fiber[] | null = null;
/** The old fiber this one was made from. null = brand new. */
alternate: Fiber | null = null;
constructor(tag: WorkTag, pendingProps: any, key: Key) {
this.tag = tag;
this.pendingProps = pendingProps;
this.key = key;
}
}
export function createFiber(tag: WorkTag, pendingProps: any, key: Key): Fiber {
return new Fiber(tag, pendingProps, key);
}
export function createFiberFromElement(element: ReactElement): Fiber {
const tag = typeof element.type === 'function' ? FunctionComponent : HostComponent;
const fiber = createFiber(tag, element.props, element.key);
fiber.type = element.type;
return fiber;
}
/** A copy of an old fiber for the new render: new props, clean flags. */
export function createWorkInProgress(current: Fiber, pendingProps: any): Fiber {
const workInProgress = createFiber(current.tag, pendingProps, current.key);
workInProgress.type = current.type;
workInProgress.stateNode = current.stateNode;
workInProgress.alternate = current;
workInProgress.child = current.child;
workInProgress.sibling = current.sibling;
workInProgress.index = current.index;
return workInProgress;
}createWorkInProgress makes the copy a reused fiber starts from: same tag,
type and key, new props, clean flags, and alternate pointing back at the old one.
Three outcomes: delete, reuse, create
For one child, only three things can happen. Here they are on a shopping list that changed between two renders:
- Reuse. Milk and Bread are still there, with the same key and the same type. They keep their fibers, and with them their state and their DOM node. Milk only gets new props: ×2.
- Delete. Eggs is gone. Its old fiber goes on the parent’s list of deletions, for the commit to remove.
- Create. Apples has no old fiber to reuse, so it gets a brand new one. The same happens when a key matches but the type changed.
A fiber survives only when key and type both agree. Deleting does not delete
anything yet: it is a note on the parent, because a deleted fiber is not in the
new list and nothing else would point at it. The four small functions that do
this (deleteChild, useFiber, updateElement, createChild) are at the top
of the full file, under The three steps.
Finding the old fiber
Which old fiber do we offer for a new child? The cheap answer is the one at the same position. The expensive answer is a lookup by key. The cheap one is a single line:
/** Try to reuse `oldFiber` for `newChild` at the same position. null = keys don't match. */
function updateSlot(returnFiber: Fiber, oldFiber: Fiber, newChild: ReactElement): Fiber | null {
return newChild.key === oldFiber.key ? updateElement(returnFiber, oldFiber, newChild) : null;
}Add one row at the top of a list and watch where the text typed in a row ends up:
No keys: by position
The fiber that held Milk’s input now shows Eggs: the text typed for Milk jumps to the wrong row, and Bread gets a new fiber.
With keys: by key
Each fiber follows its item: the typed text stays with Milk, and only Eggs gets a new fiber.
A fiber is where a component's state and its DOM node live. Match by position, and the fibers stay put while the content slides through them.
Who moved?
I walk the new list from left to right and keep one number, lastPlacedIndex:
the highest old index among the children left in place so far. Think of it as a
marker on the old list that never goes down. Here it is on the two moves from the
top of the lesson:
Variables
- newIdx
- 3
- lastPlacedIndex
- 3
- existingChildren
- { }
- returnFiber.deletions
- null
Step 1 of 10
- Last to front:
A B C DbecomesD A B C. The marker starts at 0. - The first new child is D, from old index 3. Not left of the marker: it stays, and the marker jumps to 3, the far right.
- A comes from 0, left of the marker:
Placement. - B comes from 1, also left of the marker:
Placement. The marker never goes down. - C too. The item I moved is the only one that stays: three flags for one move. That is the worst case.
- First to back:
A B C DbecomesB C D A, the mirror image. - B comes from 1: it stays, and the marker moves to 1.
- C comes from 2, still going up: it stays, and the marker follows.
- D comes from 3: it stays too.
- Only A, from 0, is behind the marker. One flag for one move.
Highlighted line: 1.
Highlighted lines: 4 to 5, 10.
Highlighted lines: 6 to 8.
Highlighted lines: 6 to 8.
Highlighted lines: 6 to 8.
Highlighted line: 1.
Highlighted lines: 4 to 5, 10.
Highlighted lines: 4 to 5, 10.
Highlighted lines: 4 to 5, 10.
Highlighted lines: 6 to 8.
function placeChild(newFiber: Fiber, lastPlacedIndex: number, newIndex: number): number {
newFiber.index = newIndex;
const current = newFiber.alternate;
if (current !== null) {
const oldIndex = current.index;
if (oldIndex < lastPlacedIndex) {
newFiber.flags |= Placement; // reused, but it moved
return lastPlacedIndex;
}
return oldIndex; // reused and it can stay where it is
}
newFiber.flags |= Placement; // brand new: insert it
return lastPlacedIndex;
}React does not search for the smallest set of moves. It makes one pass with one number, and accepts that moving an item towards the front is expensive.
The three steps
The whole function, run on a list where something is kept, something moves, something is new and something goes:
Variables
- newIdx
- 5
- lastPlacedIndex
- 4
- existingChildren
- { }
- returnFiber.deletions
- [D]
Step 1 of 11
- Old fibers
A B C D E, new childrenA B E C X. Two cursors,oldFiberandnewIdx, and the markerlastPlacedIndexat 0. - Step 1 walks both lists together. Same key, same type: A reuses its old fiber. It was at 0, not left of the marker, so it stays.
- B matches too, and the marker moves to 1. Most renders reorder nothing, so most diffs never leave this loop.
- E against C: the keys differ.
updateSlotreturnsnulland step 1 stops, with no map built. - Step 2 is for the two easy endings: no new children left (delete the rest) or no old fibers left (create the rest, which is what a first render looks like). Here both lists still have items.
- Step 3: the old fibers left go in a map, by key: C, D and E.
- E is in the map, at old index 4: right of the marker. It stays, the marker jumps to 4, and E leaves the map so it isn’t deleted.
- C comes from old index 2, left of the marker: something that was behind it is now in front. Reused, with
Placement: it moved. - X is not in the map: a brand new fiber, with
Placementto insert it. - Nobody claimed D, the last fiber in the map: it goes on the parent’s
deletions. - One pass: A, B and E stay, C moves, X is inserted, D is deleted. Every child was visited once.
Highlighted lines: 2 to 6.
Highlighted lines: 16, 22 to 24.
Highlighted lines: 16, 22 to 24.
Highlighted line: 17.
Highlighted lines: 28, 34.
Highlighted line: 44.
Highlighted lines: 46 to 51.
Highlighted lines: 46 to 51.
Highlighted line: 46.
Highlighted line: 54.
Highlighted lines: 54 to 55.
export function reconcileChildrenArray(returnFiber: Fiber, currentFirstChild: Fiber | null, newChildren: ReactElement[]): Fiber | null {
let resultingFirstChild: Fiber | null = null;
let previousNewFiber: Fiber | null = null;
let oldFiber = currentFirstChild;
let lastPlacedIndex = 0;
let newIdx = 0;
const link = (fiber: Fiber) => {
if (previousNewFiber === null) resultingFirstChild = fiber;
else previousNewFiber.sibling = fiber;
previousNewFiber = fiber;
};
// Step 1: in-order matching.
for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) {
const newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx]);
if (newFiber === null) break; // keys differ: go to the slow path
if (newFiber.alternate === null) {
// Same key, but we couldn't reuse the fiber (type changed): delete the old one.
deleteChild(returnFiber, oldFiber);
}
lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
link(newFiber);
oldFiber = oldFiber.sibling;
}
// Step 2a: new children exhausted.
if (newIdx === newChildren.length) {
deleteRemainingChildren(returnFiber, oldFiber);
return resultingFirstChild;
}
// Step 2b: old children exhausted, the rest are insertions.
if (oldFiber === null) {
for (; newIdx < newChildren.length; newIdx++) {
const newFiber = createChild(returnFiber, newChildren[newIdx]);
lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
link(newFiber);
}
return resultingFirstChild;
}
// Step 3: keyed lookup.
const existingChildren = mapRemainingChildren(oldFiber);
for (; newIdx < newChildren.length; newIdx++) {
const newFiber = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx]);
if (newFiber.alternate !== null) {
// It was reused: remove it from the map so it isn't deleted.
existingChildren.delete(newFiber.key === null ? newIdx : newFiber.key);
}
lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
link(newFiber);
}
existingChildren.forEach((child) => deleteChild(returnFiber, child));
return resultingFirstChild;
}Every new child is visited once and every old fiber once, so the work is linear. The function never looks at another parent. A child that moves to a different parent is a delete in one place and a create in the other.
The full src/child-fiber.ts
import { type Fiber, ChildDeletion, Placement, createFiberFromElement, createWorkInProgress } from './fiber.ts';
import type { ReactElement } from './shared.ts';
function deleteChild(returnFiber: Fiber, childToDelete: Fiber): void {
if (returnFiber.deletions === null) {
returnFiber.deletions = [childToDelete];
returnFiber.flags |= ChildDeletion;
} else {
returnFiber.deletions.push(childToDelete);
}
}
function deleteRemainingChildren(returnFiber: Fiber, currentFirstChild: Fiber | null): null {
let child = currentFirstChild;
while (child !== null) {
deleteChild(returnFiber, child);
child = child.sibling;
}
return null;
}
/** Reuse an existing fiber with new props. */
function useFiber(fiber: Fiber, pendingProps: any): Fiber {
const clone = createWorkInProgress(fiber, pendingProps);
clone.index = 0;
clone.sibling = null;
return clone;
}
/** Reuse `current` if the type matches, otherwise create a new fiber. */
function updateElement(returnFiber: Fiber, current: Fiber | null, element: ReactElement): Fiber {
if (current !== null && current.type === element.type) {
const existing = useFiber(current, element.props);
existing.return = returnFiber;
return existing;
}
return createChild(returnFiber, element);
}
function createChild(returnFiber: Fiber, newChild: ReactElement): Fiber {
const created = createFiberFromElement(newChild);
created.return = returnFiber;
return created;
}
/** Try to reuse `oldFiber` for `newChild` at the same position. null = keys don't match. */
function updateSlot(returnFiber: Fiber, oldFiber: Fiber, newChild: ReactElement): Fiber | null {
return newChild.key === oldFiber.key ? updateElement(returnFiber, oldFiber, newChild) : null;
}
/** The old fibers that are left, by key. Children without a key go in by index. */
function mapRemainingChildren(currentFirstChild: Fiber): Map<string | number, Fiber> {
const existingChildren = new Map<string | number, Fiber>();
let existingChild: Fiber | null = currentFirstChild;
while (existingChild !== null) {
existingChildren.set(existingChild.key !== null ? existingChild.key : existingChild.index, existingChild);
existingChild = existingChild.sibling;
}
return existingChildren;
}
function updateFromMap(existingChildren: Map<string | number, Fiber>, returnFiber: Fiber, newIdx: number, newChild: ReactElement): Fiber {
const matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) ?? null;
return updateElement(returnFiber, matchedFiber, newChild);
}
function placeChild(newFiber: Fiber, lastPlacedIndex: number, newIndex: number): number {
newFiber.index = newIndex;
const current = newFiber.alternate;
if (current !== null) {
const oldIndex = current.index;
if (oldIndex < lastPlacedIndex) {
newFiber.flags |= Placement; // reused, but it moved
return lastPlacedIndex;
}
return oldIndex; // reused and it can stay where it is
}
newFiber.flags |= Placement; // brand new: insert it
return lastPlacedIndex;
}
export function reconcileChildrenArray(returnFiber: Fiber, currentFirstChild: Fiber | null, newChildren: ReactElement[]): Fiber | null {
let resultingFirstChild: Fiber | null = null;
let previousNewFiber: Fiber | null = null;
let oldFiber = currentFirstChild;
let lastPlacedIndex = 0;
let newIdx = 0;
const link = (fiber: Fiber) => {
if (previousNewFiber === null) resultingFirstChild = fiber;
else previousNewFiber.sibling = fiber;
previousNewFiber = fiber;
};
// Step 1: in-order matching.
for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) {
const newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx]);
if (newFiber === null) break; // keys differ: go to the slow path
if (newFiber.alternate === null) {
// Same key, but we couldn't reuse the fiber (type changed): delete the old one.
deleteChild(returnFiber, oldFiber);
}
lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
link(newFiber);
oldFiber = oldFiber.sibling;
}
// Step 2a: new children exhausted.
if (newIdx === newChildren.length) {
deleteRemainingChildren(returnFiber, oldFiber);
return resultingFirstChild;
}
// Step 2b: old children exhausted, the rest are insertions.
if (oldFiber === null) {
for (; newIdx < newChildren.length; newIdx++) {
const newFiber = createChild(returnFiber, newChildren[newIdx]);
lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
link(newFiber);
}
return resultingFirstChild;
}
// Step 3: keyed lookup.
const existingChildren = mapRemainingChildren(oldFiber);
for (; newIdx < newChildren.length; newIdx++) {
const newFiber = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx]);
if (newFiber.alternate !== null) {
// It was reused: remove it from the map so it isn't deleted.
existingChildren.delete(newFiber.key === null ? newIdx : newFiber.key);
}
lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
link(newFiber);
}
existingChildren.forEach((child) => deleteChild(returnFiber, child));
return resultingFirstChild;
}useFiber is not a hook; the name is older than hooks. It resets index and
sibling, which still describe the old fiber's place in the old list.
Running it
The demo builds elements by hand, renders an old list (no old fibers, so everything is created), then diffs a new list against it. Five cases; for each, guess which fibers survive and which get a flag before you step:
Variables
- newIdx
- 4
- lastPlacedIndex
- 3
- existingChildren
- —
- returnFiber.deletions
- [B]
Step 1 of 10
- Append:
[A B C]becomes[A B C D]. Which fibers survive, and which get a flag? - Step 1 matches A, B and C in order. Then no old fibers are left, so step 2 creates D: one new fiber, one
Placement. - Remove from the middle:
[A B C D]becomes[A B D]. - D goes from index 3 to 2 and gets no flag: the marker was at 1 and D comes from 3, so it stays. A changed index is not a move. C is deleted.
- Last to front:
[A B C D]becomes[D A B C]. - D, from old index 3, puts the marker at the far right, so A, B and C are all flagged: n − 1 flags for one item moved.
- First to back:
[A B C D]becomes[B C D A]. - B, C and D come from 1, 2 and 3, going up. Only A is behind the marker: one flag.
- No keys, one type change: the same reorder as last to front, but no child has a key, and A is now a
<p>. - Every pair matches by position (
null === null): the fiber that was A now shows D, the one that was C shows B. The content slides through the fibers. Slot 1 matched by key but not by type, so the old B is deleted and a newpis created.
Highlighted line: 1.
Highlighted line: 1.
Highlighted line: 2.
Highlighted line: 2.
Highlighted line: 3.
Highlighted line: 3.
Highlighted line: 4.
Highlighted line: 4.
Highlighted line: 5.
Highlighted line: 5.
run('append', keyed('ABC'), keyed('ABCD'));
run('remove from the middle', keyed('ABCD'), keyed('ABD'));
run('last to front', keyed('ABCD'), keyed('DABC'));
run('first to back', keyed('ABCD'), keyed('BCDA'));
run('no keys, one type change', unkeyed('ABCD'), [el('li', null, 'D'), el('p', null, 'A'), el('li', null, 'B'), el('li', null, 'C')]);The demo's code and what it prints
import { REACT_ELEMENT_TYPE, type ReactElement } from './shared.ts';
import { Placement, createFiberFromElement } from './fiber.ts';
import { reconcileChildrenArray } from './child-fiber.ts';
// What <li key="A">A</li> compiles to (the Elements & JSX lesson), built by hand.
const el = (type: string, key: string | null, children: string): ReactElement => ({
$$typeof: REACT_ELEMENT_TYPE,
type,
key,
props: { children },
});
const keyed = (names: string) => [...names].map((name) => el('li', name, name));
const unkeyed = (names: string) => [...names].map((name) => el('li', null, name));
const names = (children: ReactElement[]) => children.map((child) => child.props.children).join(' ');
function run(title: string, oldChildren: ReactElement[], newChildren: ReactElement[]): void {
const parent = createFiberFromElement(el('ul', null, ''));
// "First render": there are no old fibers, so every child is created.
const oldFirstChild = reconcileChildrenArray(parent, null, oldChildren);
// "Second render": the diff we care about.
parent.child = reconcileChildrenArray(parent, oldFirstChild, newChildren);
console.log(`\n${title}: [${names(oldChildren)}] -> [${names(newChildren)}]`);
for (let fiber = parent.child; fiber !== null; fiber = fiber.sibling) {
const old = fiber.alternate;
const how = old === null ? 'created' : `reused ${old.pendingProps.children} (was at ${old.index})`;
const flag = fiber.flags & Placement ? 'Placement' : '-';
console.log(` ${fiber.index} ${fiber.pendingProps.children} ${fiber.type.padEnd(4)}${how.padEnd(22)}${flag}`);
}
const deletions = (parent.deletions ?? []).map((fiber) => fiber.pendingProps.children);
console.log(` deletions: ${deletions.join(' ') || 'none'}`);
}
run('append', keyed('ABC'), keyed('ABCD'));
run('remove from the middle', keyed('ABCD'), keyed('ABD'));
run('last to front', keyed('ABCD'), keyed('DABC'));
run('first to back', keyed('ABCD'), keyed('BCDA'));
run('no keys, one type change', unkeyed('ABCD'), [el('li', null, 'D'), el('p', null, 'A'), el('li', null, 'B'), el('li', null, 'C')]);node src/demo.ts (Node 24 runs TypeScript directly) prints:
append: [A B C] -> [A B C D]
0 A li reused A (was at 0) -
1 B li reused B (was at 1) -
2 C li reused C (was at 2) -
3 D li created Placement
deletions: none
remove from the middle: [A B C D] -> [A B D]
0 A li reused A (was at 0) -
1 B li reused B (was at 1) -
2 D li reused D (was at 3) -
deletions: C
last to front: [A B C D] -> [D A B C]
0 D li reused D (was at 3) -
1 A li reused A (was at 0) Placement
2 B li reused B (was at 1) Placement
3 C li reused C (was at 2) Placement
deletions: none
first to back: [A B C D] -> [B C D A]
0 B li reused B (was at 1) -
1 C li reused C (was at 2) -
2 D li reused D (was at 3) -
3 A li reused A (was at 0) Placement
deletions: none
no keys, one type change: [A B C D] -> [D A B C]
0 D li reused A (was at 0) -
1 A p created Placement
2 B li reused C (was at 2) -
3 C li reused D (was at 3) -
deletions: BWhat I simplified
createWorkInProgressis a plain copy. The real one recycles fibers between two trees.- Elements are built by hand with a small helper instead of JSX.
- On a first render real React does not flag each child; it flags only the root of the new subtree. Here the first call flags everything and nobody reads it.
- Only arrays of elements. A single child, text, fragments and
nullholes in the array each have their own small branch in React. - No DOM. The result is only flags.
Where this goes
Right now Placement and deletions are notes nobody reads. In the next
milestone, Reconciler, a commit phase reads them: Placement becomes an
insert, deletions become removals, and rendering the same list twice in a
browser shows exactly the three moves this function predicted.