Rendering twice
Milestone: Reconciler
Lesson 6 of 2424 min
In this lesson
The React I built in the first milestone, First paint, could paint and could not repaint.
Calling root.render(<App count={1} />) a second time rebuilt every fiber and
every DOM node, and appended a second copy of the app under the first. One
character had changed.
To change one character it would need three things:
- Remember what is on screen. The First paint version forgets everything once it has painted.
- Compare the new render with the old one. That is the keyed diff from the Keyed diff lesson, which so far only printed flags in a terminal.
- Apply the difference to the DOM, and nothing else.
This lesson puts them together. At the end, a demo page prints every DOM operation a render costs, and the numbers are the ones the Keyed diff lesson predicted.
The starting point
src/mini-react/ is a copy of the library from First paint, all twelve files, unchanged. Six of
them stay that way: shared.ts, jsx-runtime.ts, jsx-dev-runtime.ts,
dom-host.ts, fiber-root.ts and root.ts. From Keyed diff I take the ten
functions of its child-fiber.ts.
Remember: two trees
Until now there was one fiber tree. From here on there are two at the same time.
Each fiber is linked to its twin by alternate, and both twins point at the
same DOM node. A render builds the right-hand tree while reading the left-hand
one; a commit ends by pointing root.current at the tree it just built. Step
through it on a small tree, HostRoot > App > div > (Header > h1,
Counter > button), with createWorkInProgress, the function that makes the
twins, beside it:
Step 1 of 4
- After the first paint only
HostRoothas a twin inalternate: the first render’screateWorkInProgress(root.current, null)made it. Every other fiber’salternateis null. - An update starts a render. In
prepareFreshStack,createWorkInProgressreuses the twinHostRootalready has. For every other fiber the diff keeps (inuseFiber), it creates a new twin, copies the fields across and linksalternateboth ways. commitRootapplies the DOM changes, then setsroot.current = finishedWork. Only a pointer moves: the tree on the right is now current.- The next render finds
current.alternatealready there: the fiber from two renders ago.createWorkInProgressreuses that object and wipes its old flags instead of allocating a new one.
Highlighted lines: 10 to 16.
Highlighted lines: 11 to 29.
Highlighted lines: 17 to 23.
/**
* Create (or RECYCLE) the work-in-progress version of `current`.
*
* If `current.alternate` exists, it is the fiber from two renders ago. It is
* not on screen anymore, so the object is reused instead of allocating a new one.
* What describes "the last committed result" is copied from current; what the
* previous render left for the commit is wiped.
*/
export function createWorkInProgress(current: Fiber, pendingProps: any): Fiber {
let workInProgress = current.alternate;
if (workInProgress === null) {
workInProgress = createFiber(current.tag, pendingProps, current.key);
workInProgress.type = current.type;
workInProgress.stateNode = current.stateNode;
workInProgress.alternate = current;
current.alternate = workInProgress;
} else {
workInProgress.pendingProps = pendingProps;
// This fiber is starting a fresh render: forget the notes of an older one.
workInProgress.flags = NoFlags;
workInProgress.subtreeFlags = NoFlags;
workInProgress.deletions = null;
}
// `child` points at the CURRENT children: the old list the diff will compare against.
workInProgress.child = current.child;
workInProgress.memoizedProps = current.memoizedProps;
workInProgress.memoizedState = current.memoizedState;
workInProgress.sibling = current.sibling;
workInProgress.index = current.index;
return workInProgress;
}Highlighted line: 1.
root.current = finishedWork;There are never more than two fibers per node. The twin from two renders ago is
not on screen anymore, so the object is taken back and its old notes are wiped.
child deliberately points at the current children: that is the old list the
diff will compare against, and the diff replaces it a moment later.
The notes a render leaves for the commit are flags, the same bits as real React:
// 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 Update = /* */ 1 << 2; // change the props / the text of the DOM node
export const ChildDeletion = /* */ 1 << 4; // some children must be removed (see fiber.deletions)
/** Flags the mutation pass of the commit cares about. */
export const MutationMask = Placement | Update | ChildDeletion;Placement and ChildDeletion are the flags from Keyed diff. Update is new:
the node stays where it is, but its props or its text changed. The class gets
seven fields:
index: the fiber's position among its siblings.memoizedProps: the props of the last render of this fiber that finished.pendingPropsis what it is asked to render now; comparing the two is how a render finds a change.updateQueue: on a host fiber, the names of the props that changed, waiting for the commit.flags,subtreeFlagsanddeletions: what the commit has to do with this fiber, the union of every flag below it, and the old children to remove.alternate: the twin.
The changes to src/mini-react/fiber.ts
The import becomes import { REACT_FRAGMENT_TYPE, type Key, type ReactElement } from './shared';,
there is a new tag, export const Fragment = 7;, and the flags above go under
the tags. The class:
export class Fiber {
// --- identity ---
tag: WorkTag;
key: string | null;
/** The function for a component, the tag name ('div') for a host component. */
type: any = null;
/** The real thing this fiber stands for: the DOM node, or the FiberRoot for the HostRoot. */
stateNode: any = null;
// --- tree ---
return: Fiber | null = null;
child: Fiber | null = null;
sibling: Fiber | null = null;
/** Position among its siblings. */
index = 0;
// --- inputs / outputs ---
/** Props for the render that is about to happen. For a text fiber: the string. */
pendingProps: any;
/** Props used by the last render of this fiber that finished. */
memoizedProps: any = null;
/** The fiber's own state. Only the HostRoot has one so far: { element }, what render() was given. */
memoizedState: any = null;
/** HostComponent only: the names of the props that changed, waiting for the commit. */
updateQueue: any = null;
// --- effects ---
/** What the commit has to do with THIS fiber. */
flags = NoFlags;
/** Union of the flags of every fiber below this one. Lets the commit skip clean subtrees. */
subtreeFlags = NoFlags;
/** Old children to remove during commit. */
deletions: Fiber[] | null = null;
/** The other version of this fiber (current <-> workInProgress). null = it has only one. */
alternate: Fiber | null = null;
constructor(tag: WorkTag, pendingProps: any, key: string | null) {
this.tag = tag;
this.pendingProps = pendingProps;
this.key = key;
}
}The Keyed diff lesson had a createWorkInProgress that made a plain copy. This
is the real one, the code beside the diagram:
/**
* Create (or RECYCLE) the work-in-progress version of `current`.
*
* If `current.alternate` exists, it is the fiber from two renders ago. It is
* not on screen anymore, so the object is reused instead of allocating a new one.
* What describes "the last committed result" is copied from current; what the
* previous render left for the commit is wiped.
*/
export function createWorkInProgress(current: Fiber, pendingProps: any): Fiber {
let workInProgress = current.alternate;
if (workInProgress === null) {
workInProgress = createFiber(current.tag, pendingProps, current.key);
workInProgress.type = current.type;
workInProgress.stateNode = current.stateNode;
workInProgress.alternate = current;
current.alternate = workInProgress;
} else {
workInProgress.pendingProps = pendingProps;
// This fiber is starting a fresh render: forget the notes of an older one.
workInProgress.flags = NoFlags;
workInProgress.subtreeFlags = NoFlags;
workInProgress.deletions = null;
}
// `child` points at the CURRENT children: the old list the diff will compare against.
workInProgress.child = current.child;
workInProgress.memoizedProps = current.memoizedProps;
workInProgress.memoizedState = current.memoizedState;
workInProgress.sibling = current.sibling;
workInProgress.index = current.index;
return workInProgress;
}The work loop has to use the twin. In the First paint milestone, prepareFreshStack pointed the
cursor at root.current, so the walk wrote over the only tree it had. Now it
starts on the twin, and every fiber it visits gets its twin as current. Here is
a second render of the same small tree, one unit of work at a time, with the
work loop, createWorkInProgress and beginWork beside it:
Step 1 of 9
- A second
root.render().prepareFreshStackasks for the twin ofroot.current. TheHostRootalready has one (createRootmade it), socreateWorkInProgresstakes theelsebranch: new props, old notes wiped. The cursorworkInProgresspoints at it. performUnitOfWorkon theHostRoot:currentis itsalternate, the twin on screen.beginWorkgets both.updateHostRootreconciles on the update path, and the diff reusesAppthroughuseFiber, which callscreateWorkInProgress:Apphas no twin yet, so one is made and linked both ways. The cursor moves to it.App:currentis theAppon screen.updateFunctionComponentcalls it, and the diff makes the twin ofdiv. A new twin starts withchild,memoizedPropsand the rest copied fromcurrent: itschildis the old list the diff will compare against. ThenmemoizedProps = pendingProps, and the cursor moves down.divis a host component:reconcileChildrendiffs its two children,HeaderandCounter, against the ones on screen. Both are kept, so both get a twin. The cursor goes to the first child.Headerrenders and the diff makes the twin ofh1. EverybeginWorkcall gets the pair: the fiber being built and its twin on screen.- Below
h1there is only its text, left out of the picture. When the walk runs out of children,completeUnitOfWorktakes over: it completesh1, thenHeader, which has a sibling. The cursor moves toCounter. Counterrenders, and itsbuttongets a twin the same way: created once, linked both ways, recycled on every render after this one.- The
button(its text left out too) is the last fiber.completeUnitOfWorkcompletes it, then climbsreturn:Counter,div,App,HostRoot. TheHostRoothas noreturn, soworkInProgressbecomes null: the render is done. commitRootapplies the DOM changes, then pointsroot.currentat the finished tree: the right one is on screen now. The next render starts on the left one again, and every fiber already has its twin there.
Highlighted line: 3.
Highlighted lines: 8, 10.
Highlighted lines: 12, 14.
Highlighted lines: 8, 10.
Highlighted lines: 8, 10.
Highlighted lines: 13, 24 to 28.
Highlighted lines: 8, 10.
Highlighted lines: 29 to 31.
/** Start a walk: make the work-in-progress version of the HostRoot and point the cursor at it. */
export function prepareFreshStack(root: FiberRoot): void {
workInProgress = createWorkInProgress(root.current, null);
}
function performUnitOfWork(unitOfWork: Fiber): void {
// The same fiber in the tree that is on screen. null = this fiber is new.
const current = unitOfWork.alternate;
if (walkLog.enabled) console.log(`begin ${getFiberName(unitOfWork)}`);
const next = beginWork(current, unitOfWork);
// This fiber has rendered with these props: remember them for the next comparison.
unitOfWork.memoizedProps = unitOfWork.pendingProps;
if (next === null) completeUnitOfWork(unitOfWork);
else workInProgress = next;
}
/** Complete this fiber, then move to its sibling, or complete the parent. */
function completeUnitOfWork(unitOfWork: Fiber): void {
let completedWork: Fiber | null = unitOfWork;
do {
const current: Fiber | null = completedWork.alternate;
if (walkLog.enabled) console.log(`complete ${getFiberName(completedWork)}`);
completeWork(current, completedWork);
const sibling: Fiber | null = completedWork.sibling;
if (sibling !== null) {
workInProgress = sibling;
return;
}
completedWork = completedWork.return;
workInProgress = completedWork;
} while (completedWork !== null);
}Highlighted lines: 9 to 15.
Highlighted lines: 3 to 8, 17.
Highlighted lines: 17 to 21.
Highlighted lines: 3 to 8, 17.
export function createWorkInProgress(current: Fiber, pendingProps: any): Fiber {
let workInProgress = current.alternate;
if (workInProgress === null) {
workInProgress = createFiber(current.tag, pendingProps, current.key);
workInProgress.type = current.type;
workInProgress.stateNode = current.stateNode;
workInProgress.alternate = current;
current.alternate = workInProgress;
} else {
workInProgress.pendingProps = pendingProps;
// This fiber is starting a fresh render: forget the notes of an older one.
workInProgress.flags = NoFlags;
workInProgress.subtreeFlags = NoFlags;
workInProgress.deletions = null;
}
// `child` points at the CURRENT children: the old list the diff will compare against.
workInProgress.child = current.child;
workInProgress.memoizedProps = current.memoizedProps;
workInProgress.memoizedState = current.memoizedState;
workInProgress.sibling = current.sibling;
workInProgress.index = current.index;
return workInProgress;
}Highlighted lines: 21 to 23, 39 to 43.
Highlighted lines: 34 to 35.
Highlighted lines: 7 to 10.
Highlighted lines: 3 to 4.
export function beginWork(current: Fiber | null, workInProgress: Fiber): Fiber | null {
switch (workInProgress.tag) {
case FunctionComponent:
return updateFunctionComponent(current, workInProgress, workInProgress.type, workInProgress.pendingProps);
case HostRoot:
return updateHostRoot(current, workInProgress);
case HostComponent:
case Fragment:
reconcileChildren(current, workInProgress, workInProgress.pendingProps.children);
return workInProgress.child;
case HostText:
return null; // leaf
}
throw new Error(`Unknown fiber tag ${workInProgress.tag}`);
}
export function reconcileChildren(current: Fiber | null, workInProgress: Fiber, nextChildren: any): void {
if (current === null) {
// MOUNT: this fiber was never on screen. Create the children, leave no flags.
workInProgress.child = mountChildFibers(workInProgress, null, nextChildren);
} else {
// UPDATE: compare with the children that are on screen, and flag the differences.
workInProgress.child = reconcileChildFibers(workInProgress, current.child, nextChildren);
}
}
function updateFunctionComponent(
current: Fiber | null,
workInProgress: Fiber,
Component: (props: any) => any,
nextProps: any,
): Fiber | null {
// This is the line that calls your component.
const nextChildren = Component(nextProps);
reconcileChildren(current, workInProgress, nextChildren);
return workInProgress.child;
}
function updateHostRoot(current: Fiber | null, workInProgress: Fiber): Fiber | null {
const nextChildren = workInProgress.memoizedState.element;
reconcileChildren(current, workInProgress, nextChildren);
return workInProgress.child;
}Highlighted lines: 5, 7.
function commitRoot(root: FiberRoot): void {
// The tree the render phase just finished: the alternate of the tree on screen.
const finishedWork = root.current.alternate!;
// 1. Mutation: the only call in the library that changes what the user sees.
commitMutationEffects(finishedWork);
// 2. The swap: the work-in-progress tree is now the current tree.
root.current = finishedWork;
}current is null only for a fiber that is new in this render. root.ts does
not change: render() still stores { element } on root.current, and
createWorkInProgress copies memoizedState across.
The changes to src/mini-react/work-loop.ts
With createWorkInProgress added to the import from ./fiber:
/** Start a walk: make the work-in-progress version of the HostRoot and point the cursor at it. */
export function prepareFreshStack(root: FiberRoot): void {
workInProgress = createWorkInProgress(root.current, null);
}
function performUnitOfWork(unitOfWork: Fiber): void {
// The same fiber in the tree that is on screen. null = this fiber is new.
const current = unitOfWork.alternate;
if (walkLog.enabled) console.log(`begin ${getFiberName(unitOfWork)}`);
const next = beginWork(current, unitOfWork);
// This fiber has rendered with these props: remember them for the next comparison.
unitOfWork.memoizedProps = unitOfWork.pendingProps;
if (next === null) completeUnitOfWork(unitOfWork);
else workInProgress = next;
}
/** Complete this fiber, then move to its sibling, or complete the parent. */
function completeUnitOfWork(unitOfWork: Fiber): void {
let completedWork: Fiber | null = unitOfWork;
do {
const current: Fiber | null = completedWork.alternate;
if (walkLog.enabled) console.log(`complete ${getFiberName(completedWork)}`);
completeWork(current, completedWork);
const sibling: Fiber | null = completedWork.sibling;
if (sibling !== null) {
workInProgress = sibling;
return;
}
completedWork = completedWork.return;
workInProgress = completedWork;
} while (completedWork !== null);
}Compare: the keyed diff moves in
The diff itself is already written: it is the code from Keyed diff. That lesson
used a small stand-in fiber with the same field names as the real one, so the
code works here as it is. In child-fiber.ts, First paint's version (which could
only create fibers) goes, and the Keyed diff version comes in. Three things it
didn't handle need adding: a first render, children that are not elements, and a
child that is not a list.
Mount versus update. In the Keyed diff lesson a "first render" put a Placement on
every child. For a new list of a thousand rows that would be a thousand inserts
into the live page, where First paint needed one append. So the functions now
live in a closure over one boolean, shouldTrackSideEffects, and the closure
is created twice. With false, deleteChild does nothing and placeChild
only writes the index. reconcileChildren in begin-work.ts picks one for
each fiber. Here is the first render of the demo from the end of this lesson,
its tree cut down to the counter and the list:
The demo’s fiber tree, cut down to the counter and the list: HostRoot, App, div, and under div Counter (a p with the texts "Count: ", "0" and " " and a button with "+1") and a ul with its four rows folded. HostRoot was reconciled against its twin; every other fiber is new. Only App carries Placement, and the HostRoot’s subtreeFlags hold that one Placement.
Step 1 of 5
- The first
root.render(<App />).createRootleft an emptyHostRooton screen, so the work-in-progressHostRoothas a twin: itscurrentis not null, andreconcileChildrentakes the update path. Apphas no old fiber, so the diff creates one. This parent tracks side effects, andplaceSingleChildflags the new childPlacement.- Now
Apprenders, andApphas nocurrent: its children go throughmountChildFibers, whereshouldTrackSideEffectsis false. No flags. The same holds all the way down: every fiber below is new, so every one mounts. - On the way up,
completeWorkcreates each DOM node and appends its children into it. The whole card is built in memory, off the page, and nothing belowAppcarries a flag. bubblePropertiesbringsApp’s flag up: theHostRoot’ssubtreeFlagshold onePlacement. The commit will make one DOM call,appendChild(#root, <div>), with the whole card inside.
Highlighted lines: 5 to 6, 21 to 23, 39 to 43.
Highlighted lines: 18 to 20, 34 to 35.
export function beginWork(current: Fiber | null, workInProgress: Fiber): Fiber | null {
switch (workInProgress.tag) {
case FunctionComponent:
return updateFunctionComponent(current, workInProgress, workInProgress.type, workInProgress.pendingProps);
case HostRoot:
return updateHostRoot(current, workInProgress);
case HostComponent:
case Fragment:
reconcileChildren(current, workInProgress, workInProgress.pendingProps.children);
return workInProgress.child;
case HostText:
return null; // leaf
}
throw new Error(`Unknown fiber tag ${workInProgress.tag}`);
}
export function reconcileChildren(current: Fiber | null, workInProgress: Fiber, nextChildren: any): void {
if (current === null) {
// MOUNT: this fiber was never on screen. Create the children, leave no flags.
workInProgress.child = mountChildFibers(workInProgress, null, nextChildren);
} else {
// UPDATE: compare with the children that are on screen, and flag the differences.
workInProgress.child = reconcileChildFibers(workInProgress, current.child, nextChildren);
}
}
function updateFunctionComponent(
current: Fiber | null,
workInProgress: Fiber,
Component: (props: any) => any,
nextProps: any,
): Fiber | null {
// This is the line that calls your component.
const nextChildren = Component(nextProps);
reconcileChildren(current, workInProgress, nextChildren);
return workInProgress.child;
}
function updateHostRoot(current: Fiber | null, workInProgress: Fiber): Fiber | null {
const nextChildren = workInProgress.memoizedState.element;
reconcileChildren(current, workInProgress, nextChildren);
return workInProgress.child;
}Highlighted lines: 2 to 4.
/** An only child cannot move. It needs a Placement only if it is new. */
function placeSingleChild(newFiber: Fiber): Fiber {
if (shouldTrackSideEffects && newFiber.alternate === null) newFiber.flags |= Placement;
return newFiber;
}Highlighted line: 2.
Highlighted line: 4.
/** The parent was on screen before: compare, and leave flags. */
export const reconcileChildFibers = createChildReconciler(true);
/** The parent is new: just create the fibers. */
export const mountChildFibers = createChildReconciler(false);Highlighted lines: 20 to 23.
Highlighted lines: 43 to 51.
export function completeWork(current: Fiber | null, workInProgress: Fiber): void {
const newProps = workInProgress.pendingProps;
switch (workInProgress.tag) {
case FunctionComponent:
case Fragment:
case HostRoot:
// No DOM node of their own.
bubbleProperties(workInProgress);
return;
case HostComponent: {
if (current !== null) {
// UPDATE: diff old props against new props. The DOM is changed later, in the commit.
const updatePayload = diffProperties(current.memoizedProps, newProps);
if (updatePayload !== null) {
workInProgress.updateQueue = updatePayload;
workInProgress.flags |= Update;
}
} else {
// MOUNT: create the DOM node and put the child DOM nodes inside it.
const instance = createInstance(workInProgress.type, newProps);
appendAllChildren(instance, workInProgress);
workInProgress.stateNode = instance;
}
bubbleProperties(workInProgress);
return;
}
case HostText: {
if (current !== null) {
if (current.memoizedProps !== newProps) workInProgress.flags |= Update;
} else {
workInProgress.stateNode = createTextInstance(newProps);
}
bubbleProperties(workInProgress);
return;
}
}
throw new Error(`Unknown fiber tag ${workInProgress.tag}`);
}
/** OR the flags of every child, and of everything below each child, into `subtreeFlags`. */
export function bubbleProperties(completedWork: Fiber): void {
let subtreeFlags = NoFlags;
let child = completedWork.child;
while (child !== null) {
subtreeFlags |= child.subtreeFlags | child.flags;
child = child.sibling;
}
completedWork.subtreeFlags |= subtreeFlags;
}Children that are not elements.
- Text has no key, so it is matched by position (
updateTextNode). falseandnullmake no fiber. That leaves a hole in the indexes, and theoldFiber.index > newIdxcheck in the first loop keeps a filled hole from shifting every fiber after it.- An array inside an array becomes a
Fragmentfiber, so the keys of two neighbouring.map()calls can't collide. First paint flattened them, which was fine while nobody read keys.
A child that is not an array. Most components return one element.
reconcileSingleElement looks for an old fiber with the same key: same type,
reuse it and delete the others; different type, delete everything and create.
The entry point, reconcileChildFibers, sends each kind of child to its function:
- one element:
reconcileSingleElement, thenplaceSingleChild; - an array:
reconcileChildrenArray, the three steps from Keyed diff; - text:
reconcileSingleTextNode; null,undefined, a boolean or'': nothing to draw, so every old child is deleted.
A <>…</> without a key at the top counts as its children.
The full src/mini-react/child-fiber.ts
Unchanged from Keyed diff: deleteRemainingChildren, useFiber,
mapRemainingChildren, the body of placeChild after its second line, and the
three-step structure of reconcileChildrenArray.
/**
* CHILD RECONCILIATION ("the diffing algorithm")
* ==============================================
*
* Input: the current child fibers of one parent (what is on screen)
* the new children (what the component just returned)
* Output: the work-in-progress child fibers, with flags:
* - Placement on fibers that are new or that MOVED
* - ChildDeletion on the parent, with the removed fibers in parent.deletions
*
* An old fiber is REUSED when key AND type match: its DOM node survives.
* Otherwise a new one is created.
*
* On MOUNT (the parent has no current fiber) side effects are not tracked: the
* whole new subtree is built off-screen, and only its top fiber gets one Placement.
*/
import {
type Fiber,
ChildDeletion,
Fragment,
HostText,
Placement,
createFiberFromElement,
createFiberFromFragment,
createFiberFromText,
createWorkInProgress,
} from './fiber';
import { REACT_ELEMENT_TYPE, REACT_FRAGMENT_TYPE, type ReactElement } from './shared';
function isElement(x: any): x is ReactElement {
return typeof x === 'object' && x !== null && x.$$typeof === REACT_ELEMENT_TYPE;
}
function isText(x: any): x is string | number {
return (typeof x === 'string' && x !== '') || typeof x === 'number';
}
function createChildReconciler(shouldTrackSideEffects: boolean) {
function deleteChild(returnFiber: Fiber, childToDelete: Fiber): void {
if (!shouldTrackSideEffects) return;
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 it is a text fiber, otherwise create one. */
function updateTextNode(returnFiber: Fiber, current: Fiber | null, textContent: string): Fiber {
if (current === null || current.tag !== HostText) {
const created = createFiberFromText(textContent);
created.return = returnFiber;
return created;
}
const existing = useFiber(current, textContent);
existing.return = returnFiber;
return existing;
}
/** Reuse `current` if the type matches, otherwise create a new fiber. */
function updateElement(returnFiber: Fiber, current: Fiber | null, element: ReactElement): Fiber {
if (element.type === REACT_FRAGMENT_TYPE) {
return updateFragment(returnFiber, current, element.props.children, element.key);
}
if (current !== null && current.type === element.type) {
const existing = useFiber(current, element.props);
existing.return = returnFiber;
return existing;
}
const created = createFiberFromElement(element);
created.return = returnFiber;
return created;
}
/** Reuse `current` if it is a fragment fiber, otherwise create one. */
function updateFragment(returnFiber: Fiber, current: Fiber | null, fragment: any, key: string | null): Fiber {
if (current === null || current.tag !== Fragment) {
const created = createFiberFromFragment(fragment, key);
created.return = returnFiber;
return created;
}
const existing = useFiber(current, { children: fragment });
existing.return = returnFiber;
return existing;
}
/** One child -> one new fiber. null for the children that draw nothing. */
function createChild(returnFiber: Fiber, newChild: any): Fiber | null {
let created: Fiber;
if (isText(newChild)) created = createFiberFromText('' + newChild);
else if (isElement(newChild)) created = createFiberFromElement(newChild);
else if (Array.isArray(newChild)) created = createFiberFromFragment(newChild, null);
else return null; // null, undefined, true, false, ''
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 | null, newChild: any): Fiber | null {
const key = oldFiber !== null ? oldFiber.key : null;
if (isText(newChild)) {
if (key !== null) return null; // text has no key, the old fiber has one
return updateTextNode(returnFiber, oldFiber, '' + newChild);
}
if (isElement(newChild)) {
return newChild.key === key ? updateElement(returnFiber, oldFiber, newChild) : null;
}
if (Array.isArray(newChild)) {
if (key !== null) return null;
return updateFragment(returnFiber, oldFiber, newChild, null);
}
return null; // a child that draws nothing never matches
}
/** 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: any): Fiber | null {
if (isText(newChild)) {
return updateTextNode(returnFiber, existingChildren.get(newIdx) ?? null, '' + newChild);
}
if (isElement(newChild)) {
const matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) ?? null;
return updateElement(returnFiber, matchedFiber, newChild);
}
if (Array.isArray(newChild)) {
return updateFragment(returnFiber, existingChildren.get(newIdx) ?? null, newChild, null);
}
return null;
}
/**
* Decide whether `newFiber` needs a Placement (insert or move).
*
* `lastPlacedIndex` is the largest OLD index among the children we have kept in
* place so far. A reused child whose old index is smaller than that used to be on
* the left of a child that is now before it, so it has to move.
*
* old: A(0) B(1) C(2) new: C A B
* C: oldIndex 2 >= 0 -> stays, lastPlacedIndex = 2
* A: oldIndex 0 < 2 -> MOVE
* B: oldIndex 1 < 2 -> MOVE
*/
function placeChild(newFiber: Fiber, lastPlacedIndex: number, newIndex: number): number {
newFiber.index = newIndex;
if (!shouldTrackSideEffects) return lastPlacedIndex;
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;
}
/** An only child cannot move. It needs a Placement only if it is new. */
function placeSingleChild(newFiber: Fiber): Fiber {
if (shouldTrackSideEffects && newFiber.alternate === null) newFiber.flags |= Placement;
return newFiber;
}
/**
* Real React's algorithm, in three steps:
* 1. Walk old and new in parallel while keys match (the common "nothing moved" case).
* 2. If new ran out: delete the rest of old. If old ran out: create the rest of new.
* 3. Otherwise put the remaining old fibers in a Map by key (or index) and look each
* new child up in it. Whatever is left in the map at the end gets deleted.
*/
function reconcileChildrenArray(returnFiber: Fiber, currentFirstChild: Fiber | null, newChildren: any[]): Fiber | null {
let resultingFirstChild: Fiber | null = null;
let previousNewFiber: Fiber | null = null;
let oldFiber = currentFirstChild;
let lastPlacedIndex = 0;
let newIdx = 0;
let nextOldFiber: Fiber | null = null;
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++) {
if (oldFiber.index > newIdx) {
// The old list had a hole here (a `false` or a `null`): nothing to compare with.
nextOldFiber = oldFiber;
oldFiber = null;
} else {
nextOldFiber = oldFiber.sibling;
}
const newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx]);
if (newFiber === null) {
if (oldFiber === null) oldFiber = nextOldFiber;
break; // keys differ: go to the slow path
}
if (shouldTrackSideEffects && oldFiber && 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 = nextOldFiber;
}
// 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]);
if (newFiber === null) continue;
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 === null) continue;
if (shouldTrackSideEffects && 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);
}
if (shouldTrackSideEffects) existingChildren.forEach((child) => deleteChild(returnFiber, child));
return resultingFirstChild;
}
/** The new child is ONE piece of text. Keep the first old fiber if it is text; delete the rest. */
function reconcileSingleTextNode(returnFiber: Fiber, currentFirstChild: Fiber | null, textContent: string): Fiber {
if (currentFirstChild !== null && currentFirstChild.tag === HostText) {
deleteRemainingChildren(returnFiber, currentFirstChild.sibling);
const existing = useFiber(currentFirstChild, textContent);
existing.return = returnFiber;
return existing;
}
deleteRemainingChildren(returnFiber, currentFirstChild);
const created = createFiberFromText(textContent);
created.return = returnFiber;
return created;
}
/** The new child is ONE element. Look for an old fiber with its key and type; delete all the others. */
function reconcileSingleElement(returnFiber: Fiber, currentFirstChild: Fiber | null, element: ReactElement): Fiber {
let child = currentFirstChild;
while (child !== null) {
if (child.key === element.key) {
const sameType = element.type === REACT_FRAGMENT_TYPE ? child.tag === Fragment : child.type === element.type;
if (sameType) {
// Match: delete its siblings, reuse this one.
deleteRemainingChildren(returnFiber, child.sibling);
const existing = useFiber(child, element.props);
existing.return = returnFiber;
return existing;
}
// Same key, different type: nothing can be reused.
deleteRemainingChildren(returnFiber, child);
break;
}
deleteChild(returnFiber, child);
child = child.sibling;
}
const created = createFiberFromElement(element);
created.return = returnFiber;
return created;
}
function reconcileChildFibers(returnFiber: Fiber, currentFirstChild: Fiber | null, newChild: any): Fiber | null {
// <>...</> without a key, at the top: the same as returning its children directly.
if (isElement(newChild) && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null) {
newChild = newChild.props.children;
}
if (isElement(newChild)) {
return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild));
}
if (Array.isArray(newChild)) {
return reconcileChildrenArray(returnFiber, currentFirstChild, newChild);
}
if (isText(newChild)) {
return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, '' + newChild));
}
// null, undefined, true, false, '': nothing to draw. Whatever was there goes.
return deleteRemainingChildren(returnFiber, currentFirstChild);
}
return reconcileChildFibers;
}
/** The parent was on screen before: compare, and leave flags. */
export const reconcileChildFibers = createChildReconciler(true);
/** The parent is new: just create the fibers. */
export const mountChildFibers = createChildReconciler(false);The fragment fiber in src/mini-react/fiber.ts, and src/mini-react/begin-work.ts
fiber.ts needs the fragment fiber the reconciler asks for. getFiberName
gets a case Fragment: return 'Fragment';, and:
// Element -> fiber. The element says WHAT to render; its `type` decides the tag.
export function createFiberFromTypeAndProps(type: any, key: Key, pendingProps: any): Fiber {
let tag: WorkTag;
if (typeof type === 'function') {
tag = FunctionComponent;
} else if (typeof type === 'string') {
tag = HostComponent;
} else if (type === REACT_FRAGMENT_TYPE) {
return createFiberFromFragment(pendingProps.children, key);
} else {
throw new Error(`mini-react: unsupported element type: ${String(type)}`);
}
const fiber = createFiber(tag, pendingProps, key);
fiber.type = type;
return fiber;
}
/** A fragment has no DOM node and no function. It only groups children. */
export function createFiberFromFragment(children: any, key: Key): Fiber {
return createFiber(Fragment, { children }, key);
}beginWork passes current down, and reconcileChildren is where mount and
update split:
import { type Fiber, Fragment, FunctionComponent, HostComponent, HostRoot, HostText } from './fiber';
import { mountChildFibers, reconcileChildFibers } from './child-fiber';
export function beginWork(current: Fiber | null, workInProgress: Fiber): Fiber | null {
switch (workInProgress.tag) {
case FunctionComponent:
return updateFunctionComponent(current, workInProgress, workInProgress.type, workInProgress.pendingProps);
case HostRoot:
return updateHostRoot(current, workInProgress);
case HostComponent:
case Fragment:
reconcileChildren(current, workInProgress, workInProgress.pendingProps.children);
return workInProgress.child;
case HostText:
return null; // leaf
}
throw new Error(`Unknown fiber tag ${workInProgress.tag}`);
}
export function reconcileChildren(current: Fiber | null, workInProgress: Fiber, nextChildren: any): void {
if (current === null) {
// MOUNT: this fiber was never on screen. Create the children, leave no flags.
workInProgress.child = mountChildFibers(workInProgress, null, nextChildren);
} else {
// UPDATE: compare with the children that are on screen, and flag the differences.
workInProgress.child = reconcileChildFibers(workInProgress, current.child, nextChildren);
}
}
function updateFunctionComponent(
current: Fiber | null,
workInProgress: Fiber,
Component: (props: any) => any,
nextProps: any,
): Fiber | null {
// This is the line that calls your component.
const nextChildren = Component(nextProps);
reconcileChildren(current, workInProgress, nextChildren);
return workInProgress.child;
}
function updateHostRoot(current: Fiber | null, workInProgress: Fiber): Fiber | null {
const nextChildren = workInProgress.memoizedState.element;
reconcileChildren(current, workInProgress, nextChildren);
return workInProgress.child;
}Component(nextProps) is still unconditional. Every component is called again
on every root.render(), even with identical props. Skipping a component
safely requires knowing that nothing inside it changed, and that arrives with
state. For now only the DOM work is minimal.
Take notes on the way up
The completeWork from First paint created a DOM node for every host fiber. On a second render
the node already exists, so there is an update branch: diff the props with
diffProperties from DOM host, park the changed names on updateQueue, set
Update. Nothing touches the node yet. Then bubbleProperties folds the flags
of the children into the parent's subtreeFlags. Here is the render after a
click on the demo's +1, on its way up:
The fiber tree after a click on +1, cut down to the counter and the list. The text "1" and the button carry Update; p, Counter, div, App and HostRoot have Update in their subtreeFlags; the ul and its rows have none.
Step 1 of 8
- A click on
+1callsroot.render()withcount: 1. The render went down the tree, andcompleteWorkruns on each fiber once its children are done, so the notes are taken from the bottom up. The two rows of buttons are left out of the picture. "Count: "has the same text as last time: no flag. The next text fiber had"0"and now has"1":Update. The DOM text node still says 0.- The
buttongets a newonClickon every render, a new arrow function, anddiffPropertiesreports it:updateQueue = ["onClick"], andUpdate. - The
phas nothing of its own to change (childrenis not a prop the diff compares).bubblePropertiesORs its children’s flags into itssubtreeFlags:Update. Counterhas no DOM node, so it only bubbles:Updatein itssubtreeFlags.- The
uland its four rows: the same props, the same text. No flag anywhere, and itssubtreeFlagsstay empty. divORsCounter’sUpdatewith the list’s nothing. One level down is all it looks at: each child already carries the summary of its own subtree.AppandHostRootbubble last. The root’ssubtreeFlagssay “there is anUpdatesomewhere below”, and the empty ones on the way say where there is nothing.
Highlighted lines: 1 to 3.
Highlighted lines: 29 to 31.
Highlighted lines: 14 to 18.
Highlighted lines: 14 to 15, 43 to 51.
Highlighted lines: 4 to 9.
Highlighted lines: 14 to 15.
Highlighted lines: 43 to 51.
Highlighted lines: 4 to 9.
export function completeWork(current: Fiber | null, workInProgress: Fiber): void {
const newProps = workInProgress.pendingProps;
switch (workInProgress.tag) {
case FunctionComponent:
case Fragment:
case HostRoot:
// No DOM node of their own.
bubbleProperties(workInProgress);
return;
case HostComponent: {
if (current !== null) {
// UPDATE: diff old props against new props. The DOM is changed later, in the commit.
const updatePayload = diffProperties(current.memoizedProps, newProps);
if (updatePayload !== null) {
workInProgress.updateQueue = updatePayload;
workInProgress.flags |= Update;
}
} else {
// MOUNT: create the DOM node and put the child DOM nodes inside it.
const instance = createInstance(workInProgress.type, newProps);
appendAllChildren(instance, workInProgress);
workInProgress.stateNode = instance;
}
bubbleProperties(workInProgress);
return;
}
case HostText: {
if (current !== null) {
if (current.memoizedProps !== newProps) workInProgress.flags |= Update;
} else {
workInProgress.stateNode = createTextInstance(newProps);
}
bubbleProperties(workInProgress);
return;
}
}
throw new Error(`Unknown fiber tag ${workInProgress.tag}`);
}
/** OR the flags of every child, and of everything below each child, into `subtreeFlags`. */
export function bubbleProperties(completedWork: Fiber): void {
let subtreeFlags = NoFlags;
let child = completedWork.child;
while (child !== null) {
subtreeFlags |= child.subtreeFlags | child.flags;
child = child.sibling;
}
completedWork.subtreeFlags |= subtreeFlags;
}bubbleProperties is why the commit can be cheap. Children complete before
parents, so each fiber only looks one level down, and when the walk reaches the
root, root.subtreeFlags summarises the whole tree.
The new completeWork and bubbleProperties in src/mini-react/complete-work.ts
The imports gain Fragment, NoFlags, Update and diffProperties, and
appendAllChildren is no longer exported.
export function completeWork(current: Fiber | null, workInProgress: Fiber): void {
const newProps = workInProgress.pendingProps;
switch (workInProgress.tag) {
case FunctionComponent:
case Fragment:
case HostRoot:
// No DOM node of their own.
bubbleProperties(workInProgress);
return;
case HostComponent: {
if (current !== null) {
// UPDATE: diff old props against new props. The DOM is changed later, in the commit.
const updatePayload = diffProperties(current.memoizedProps, newProps);
if (updatePayload !== null) {
workInProgress.updateQueue = updatePayload;
workInProgress.flags |= Update;
}
} else {
// MOUNT: create the DOM node and put the child DOM nodes inside it.
const instance = createInstance(workInProgress.type, newProps);
appendAllChildren(instance, workInProgress);
workInProgress.stateNode = instance;
}
bubbleProperties(workInProgress);
return;
}
case HostText: {
if (current !== null) {
if (current.memoizedProps !== newProps) workInProgress.flags |= Update;
} else {
workInProgress.stateNode = createTextInstance(newProps);
}
bubbleProperties(workInProgress);
return;
}
}
throw new Error(`Unknown fiber tag ${workInProgress.tag}`);
}
/** OR the flags of every child, and of everything below each child, into `subtreeFlags`. */
export function bubbleProperties(completedWork: Fiber): void {
let subtreeFlags = NoFlags;
let child = completedWork.child;
while (child !== null) {
subtreeFlags |= child.subtreeFlags | child.flags;
child = child.sibling;
}
completedWork.subtreeFlags |= subtreeFlags;
}At this point the render phase is complete and the commit is still First paint's
appendAllChildren. Running the First paint demo is instructive: a click no longer adds a
second card (no new DOM nodes were created), but the count stays at 0. One text
fiber carries an Update flag, and nobody reads it.
Apply: the mutation pass
A new file, commit-work.ts, is the only one that changes the page. It walks
the finished tree and turns each flag into DOM calls: ChildDeletion removes the
nodes of the fibers in deletions, Placement inserts (or moves) a fiber's
nodes, and Update applies the changed props or the new text.
The traversal. recursivelyTraverseMutationEffects only goes down where
subtreeFlags says there is work. For each fiber: everything below it first,
then its own Placement, then its own Update. The commit of the same +1
click:
The same tree after the commit: the traversal visited HostRoot, App, div, Counter, p and its children, and the ul; the "+1" text and the ul’s rows were skipped. In the part drawn, two DOM calls: the text node’s nodeValue set from "0" to "1", then commitUpdate on the button with ["onClick"]. Each button left out gets its own commitUpdate too.
DOM calls
"0".nodeValue = "1"commitUpdate(<button>, ["onClick"])Step 1 of 6
commitMutationEffectsgets the finished tree. The flags are on the fibers; nothing on the page has changed yet. The strip shows the DOM children of thep.HostRoot,App,div,Counter,p: each hasUpdatein itssubtreeFlags, so the traversal goes into its children."Count: "has nothing to do. The next text fiber hasUpdate: its DOM node getsnodeValue = "1", the first change the page sees.- Children first: the
button’ssubtreeFlagsare empty, so"+1"is not visited. Then its ownUpdate:commitUpdateswaps theonClicklistener. The page looks the same. - The
ul’ssubtreeFlagsare empty: one check, and none of its rows is visited. Two DOM calls in the part drawn. The demo’s seven other buttons each get anUpdatefor their newonClick, so the whole commit makes nine calls, and the document sees one: the text. - The mutation pass is done and the page matches the new tree. Only now does
commitRootpointroot.currentat it: during the pass,currentstill meant the old tree, where the old props are read from.
Highlighted lines: 16 to 22.
Highlighted lines: 7 to 12.
Highlighted line: 33.
Highlighted lines: 7, 25 to 30.
Highlighted line: 7.
function recursivelyTraverseMutationEffects(parentFiber: Fiber): void {
// Deletions first. They are stored on the parent: a deleted fiber is not in the new tree.
const deletions = parentFiber.deletions;
if (deletions !== null) {
for (const childToDelete of deletions) commitDeletionEffects(parentFiber, childToDelete);
}
if (parentFiber.subtreeFlags & MutationMask) {
let child = parentFiber.child;
while (child !== null) {
commitMutationEffectsOnFiber(child);
child = child.sibling;
}
}
}
function commitMutationEffectsOnFiber(finishedWork: Fiber): void {
const current = finishedWork.alternate;
const flags = finishedWork.flags;
// Everything below this fiber first, then its own Placement, then its own Update.
recursivelyTraverseMutationEffects(finishedWork);
commitReconciliationEffects(finishedWork);
switch (finishedWork.tag) {
case HostComponent:
if (flags & Update) {
const updatePayload: string[] = finishedWork.updateQueue;
finishedWork.updateQueue = null;
commitUpdate(finishedWork.stateNode, updatePayload, current!.memoizedProps, finishedWork.memoizedProps);
}
return;
case HostText:
if (flags & Update) finishedWork.stateNode.nodeValue = finishedWork.memoizedProps;
return;
}
}
function commitReconciliationEffects(finishedWork: Fiber): void {
if (finishedWork.flags & Placement) {
commitPlacement(finishedWork);
// Done. Clear the bit so nothing takes this fiber for one that still has to be inserted.
finishedWork.flags &= ~Placement;
}
}Highlighted lines: 5, 7.
function commitRoot(root: FiberRoot): void {
// The tree the render phase just finished: the alternate of the tree on screen.
const finishedWork = root.current.alternate!;
// 1. Mutation: the only call in the library that changes what the user sees.
commitMutationEffects(finishedWork);
// 2. The swap: the work-in-progress tree is now the current tree.
root.current = finishedWork;
}Update. For an element, commitUpdate from DOM host gets the list of
changed props, the old props (from current, which is what the second tree is
for) and the new ones. A new onClick function is a changed prop, so the
temporary addEventListener shortcut keeps working: the old listener is
removed and the new one added. For text, the node gets the new string.
Placement. Two questions: which DOM parent, and where in it. The parent is
the nearest ancestor with a DOM node (getHostParentFiber); components and
fragments have none. "Where" is the hard part. insertBefore needs the DOM
node that comes right after ours, and that is not fiber.sibling.stateNode,
for three reasons, all handled by getHostSibling:
- the sibling fiber may be a component or a fragment, so its DOM node is somewhere inside it;
- the sibling may carry a
Placementitself, in which case its node is about to move (or is not in the document yet) and cannot be an anchor; - there may be no sibling at this level while a DOM node still follows, next to a parent that is a component or a fragment.
If the search finds nothing stable, the node is appended. If the placed fiber
is itself a component or a fragment, insertOrAppendPlacementNode places each
of its top-level DOM nodes. Here are the rows of the list after last to front,
the case Keyed diff flagged three times:
The fibers of the keyed list after last to front: Row D, Row A, Row B and Row C under the ul, each with its li. The DOM children of the ul end in the order D A B C, after three appendChild calls, for the li of A, B and C. Row D was never touched.
DOM calls
appendChild(<ul>, <li>A)appendChild(<ul>, <li>B)appendChild(<ul>, <li>C)Step 1 of 6
- The list after
last to front; only the list is drawn. The diff leftPlacementon rows A, B and C, and D stays. The DOM still has the old order. - Down to the
ul.Row Dcomes first: no flags, emptysubtreeFlags, nothing to do. Row A: its children first (nothing), then itsPlacement. ARowhas no DOM node, so the parent is the nearest host ancestor, theul. Where in it?getHostSiblingtriesRow BandRow C: both carryPlacement, so they are about to move and can’t be anchors. Then no sibling is left, and the parent is a host node: nothing stable comes after A.- So A is appended.
insertOrAppendPlacementNodegoes into theRowto itsliand callsappendChild: the node moves to the end. ThePlacementbit is cleared. Row B:Row Cstill hasPlacement, so B is appended too.Row Chas no sibling: appended. D A B C in three moves, the three flags from Keyed diff. D, the row that “moved”, was never touched.
Highlighted lines: 39 to 43.
Highlighted lines: 7 to 12.
Highlighted line: 42.
function recursivelyTraverseMutationEffects(parentFiber: Fiber): void {
// Deletions first. They are stored on the parent: a deleted fiber is not in the new tree.
const deletions = parentFiber.deletions;
if (deletions !== null) {
for (const childToDelete of deletions) commitDeletionEffects(parentFiber, childToDelete);
}
if (parentFiber.subtreeFlags & MutationMask) {
let child = parentFiber.child;
while (child !== null) {
commitMutationEffectsOnFiber(child);
child = child.sibling;
}
}
}
function commitMutationEffectsOnFiber(finishedWork: Fiber): void {
const current = finishedWork.alternate;
const flags = finishedWork.flags;
// Everything below this fiber first, then its own Placement, then its own Update.
recursivelyTraverseMutationEffects(finishedWork);
commitReconciliationEffects(finishedWork);
switch (finishedWork.tag) {
case HostComponent:
if (flags & Update) {
const updatePayload: string[] = finishedWork.updateQueue;
finishedWork.updateQueue = null;
commitUpdate(finishedWork.stateNode, updatePayload, current!.memoizedProps, finishedWork.memoizedProps);
}
return;
case HostText:
if (flags & Update) finishedWork.stateNode.nodeValue = finishedWork.memoizedProps;
return;
}
}
function commitReconciliationEffects(finishedWork: Fiber): void {
if (finishedWork.flags & Placement) {
commitPlacement(finishedWork);
// Done. Clear the bit so nothing takes this fiber for one that still has to be inserted.
finishedWork.flags &= ~Placement;
}
}Highlighted lines: 23, 26, 29.
Highlighted lines: 47, 51 to 55.
Highlighted lines: 47, 51 to 55.
Highlighted lines: 47, 51 to 55.
/** The nearest ancestor that has a DOM node: components and fragments have none. */
function getHostParentFiber(fiber: Fiber): Fiber {
let parent = fiber.return;
while (parent !== null) {
if (isHostParent(parent)) return parent;
parent = parent.return;
}
throw new Error('Expected to find a host parent.');
}
/**
* Find the DOM node we must insert BEFORE: the next host node to the right in
* the fiber tree that is already at its place, i.e. NOT flagged Placement itself.
* The search goes through siblings, down into components and fragments (they
* have no DOM node of their own) and up through parents that are not host nodes.
* null = nothing stable comes after us: append.
*/
function getHostSibling(fiber: Fiber): Node | null {
let node: Fiber = fiber;
siblings: while (true) {
// No sibling: climb. A host parent ends the search, nothing comes after us inside it.
while (node.sibling === null) {
if (node.return === null || isHostParent(node.return)) return null;
node = node.return;
}
node = node.sibling;
// Not a DOM node: look inside it for its first one.
while (node.tag !== HostComponent && node.tag !== HostText) {
if (node.flags & Placement) continue siblings; // it is being placed too: its nodes are not stable
if (node.child === null) continue siblings; // it renders nothing
node = node.child;
}
if (!(node.flags & Placement)) return node.stateNode;
}
}
function commitPlacement(finishedWork: Fiber): void {
const parentFiber = getHostParentFiber(finishedWork);
const parent: Node = parentFiber.tag === HostRoot ? parentFiber.stateNode.containerInfo : parentFiber.stateNode;
const before = getHostSibling(finishedWork);
insertOrAppendPlacementNode(finishedWork, before, parent);
}
function insertOrAppendPlacementNode(node: Fiber, before: Node | null, parent: Node): void {
if (node.tag === HostComponent || node.tag === HostText) {
if (before) insertBefore(parent, node.stateNode, before);
else appendChild(parent, node.stateNode);
return;
}
// A component or a fragment: insert each of its top-level host nodes.
let child = node.child;
while (child !== null) {
insertOrAppendPlacementNode(child, before, parent);
child = child.sibling;
}
}Deletion. A deleted fiber is not in the new tree, which is why Keyed diff
stored it on its parent: the commit reaches the parent and runs its deletions
before going into the children. A deleted DOM node is removed with one
removeChild and everything inside leaves with it; a deleted component has no
node, so the search goes down to the nodes it rendered. Switching the demo's
list from ul to ol deletes one fiber and places another:
The tree after the list switched from ul to ol, with the counter and the keys button left out and the first row of buttons folded: div has ChildDeletion and the old ul on its deletions, the new ol carries Placement, and the list button and its text "ol" carry Update. The DOM children of div go from ul, p, p to ol, p, p.
DOM calls
removeChild(<div>, <ul>)insertBefore(<div>, <ol>, <p>1)"ul".nodeValue = "ol"commitUpdate(<button>, ["onClick"])Step 1 of 7
- The list button switched
ultool(the counter and the keys button are left out, and the first row of buttons is folded: those buttons each get anUpdatetoo, not drawn). Same position, different type: the diff put the oldulondiv.deletions, withChildDeletion, and created anolwithPlacement, built off-screen with its rows. - Down to the
div: aChildDeletionof its own, andPlacementandUpdatein itssubtreeFlags. - Deletions first. The old
ulis a DOM node: oneremoveChild, and its rows, inputs and typed text leave with it. Nothing inside it is visited. - Then the children. The
ol’s subtree was built off-screen, with no flags: skipped. Then its ownPlacement: the next sibling is the firstp, the row of buttons: a DOM node withoutPlacement, so a stable anchor. insertBefore(<div>, <ol>, <p>1): the new list, with everything inside it, goes in with one call, right where theulwas.- The row of buttons is visited (its five
commitUpdatecalls aren’t drawn), then the secondpand the list button’s label: the text fiber that said"ul"hasUpdate, and its node getsnodeValue = "ol". - Last, the button’s own
Update, its newonClick. Four DOM calls in the part drawn. With the counter’s button, the five folded ones and the keys button (not drawn), each swapping itsonClick, the whole commit makes eleven; the document sees three.
Highlighted lines: 3 to 6.
Highlighted lines: 7 to 12.
Highlighted lines: 3 to 6.
Highlighted line: 33.
Highlighted lines: 25 to 30.
function recursivelyTraverseMutationEffects(parentFiber: Fiber): void {
// Deletions first. They are stored on the parent: a deleted fiber is not in the new tree.
const deletions = parentFiber.deletions;
if (deletions !== null) {
for (const childToDelete of deletions) commitDeletionEffects(parentFiber, childToDelete);
}
if (parentFiber.subtreeFlags & MutationMask) {
let child = parentFiber.child;
while (child !== null) {
commitMutationEffectsOnFiber(child);
child = child.sibling;
}
}
}
function commitMutationEffectsOnFiber(finishedWork: Fiber): void {
const current = finishedWork.alternate;
const flags = finishedWork.flags;
// Everything below this fiber first, then its own Placement, then its own Update.
recursivelyTraverseMutationEffects(finishedWork);
commitReconciliationEffects(finishedWork);
switch (finishedWork.tag) {
case HostComponent:
if (flags & Update) {
const updatePayload: string[] = finishedWork.updateQueue;
finishedWork.updateQueue = null;
commitUpdate(finishedWork.stateNode, updatePayload, current!.memoizedProps, finishedWork.memoizedProps);
}
return;
case HostText:
if (flags & Update) finishedWork.stateNode.nodeValue = finishedWork.memoizedProps;
return;
}
}
function commitReconciliationEffects(finishedWork: Fiber): void {
if (finishedWork.flags & Placement) {
commitPlacement(finishedWork);
// Done. Clear the bit so nothing takes this fiber for one that still has to be inserted.
finishedWork.flags &= ~Placement;
}
}Highlighted lines: 24 to 25.
/** The DOM node the deletion in progress removes from. */
let hostParent: Node | null = null;
function commitDeletionEffects(returnFiber: Fiber, deletedFiber: Fiber): void {
// `returnFiber` may be the host parent itself (a <ul> losing an <li>), so the search starts AT it.
const parentFiber = isHostParent(returnFiber) ? returnFiber : getHostParentFiber(returnFiber);
hostParent = parentFiber.tag === HostRoot ? parentFiber.stateNode.containerInfo : parentFiber.stateNode;
commitDeletionEffectsOnFiber(deletedFiber);
hostParent = null;
}
function recursivelyTraverseDeletionEffects(parent: Fiber): void {
let child = parent.child;
while (child !== null) {
commitDeletionEffectsOnFiber(child);
child = child.sibling;
}
}
function commitDeletionEffectsOnFiber(deletedFiber: Fiber): void {
switch (deletedFiber.tag) {
case HostComponent:
case HostText:
// One removal. Do NOT go below it: everything inside leaves the page with it.
if (hostParent !== null) removeChild(hostParent, deletedFiber.stateNode);
return;
default:
// A component or a fragment has no DOM node: its nodes are further down.
recursivelyTraverseDeletionEffects(deletedFiber);
}
}Highlighted lines: 26, 33.
Highlighted line: 46.
/** The nearest ancestor that has a DOM node: components and fragments have none. */
function getHostParentFiber(fiber: Fiber): Fiber {
let parent = fiber.return;
while (parent !== null) {
if (isHostParent(parent)) return parent;
parent = parent.return;
}
throw new Error('Expected to find a host parent.');
}
/**
* Find the DOM node we must insert BEFORE: the next host node to the right in
* the fiber tree that is already at its place, i.e. NOT flagged Placement itself.
* The search goes through siblings, down into components and fragments (they
* have no DOM node of their own) and up through parents that are not host nodes.
* null = nothing stable comes after us: append.
*/
function getHostSibling(fiber: Fiber): Node | null {
let node: Fiber = fiber;
siblings: while (true) {
// No sibling: climb. A host parent ends the search, nothing comes after us inside it.
while (node.sibling === null) {
if (node.return === null || isHostParent(node.return)) return null;
node = node.return;
}
node = node.sibling;
// Not a DOM node: look inside it for its first one.
while (node.tag !== HostComponent && node.tag !== HostText) {
if (node.flags & Placement) continue siblings; // it is being placed too: its nodes are not stable
if (node.child === null) continue siblings; // it renders nothing
node = node.child;
}
if (!(node.flags & Placement)) return node.stateNode;
}
}
function commitPlacement(finishedWork: Fiber): void {
const parentFiber = getHostParentFiber(finishedWork);
const parent: Node = parentFiber.tag === HostRoot ? parentFiber.stateNode.containerInfo : parentFiber.stateNode;
const before = getHostSibling(finishedWork);
insertOrAppendPlacementNode(finishedWork, before, parent);
}
function insertOrAppendPlacementNode(node: Fiber, before: Node | null, parent: Node): void {
if (node.tag === HostComponent || node.tag === HostText) {
if (before) insertBefore(parent, node.stateNode, before);
else appendChild(parent, node.stateNode);
return;
}
// A component or a fragment: insert each of its top-level host nodes.
let child = node.child;
while (child !== null) {
insertOrAppendPlacementNode(child, before, parent);
child = child.sibling;
}
}The full src/mini-react/commit-work.ts
/**
* COMMIT PHASE: the mutation pass
* ===============================
*
* The render phase produced a finished work-in-progress tree whose fibers carry
* flags. This file reads the flags and touches the DOM. Nothing else does.
*
* ChildDeletion remove the DOM nodes of the fibers in `fiber.deletions`
* Placement insert (or move) the fiber's DOM nodes at their place
* Update apply the changed props, or the new text
*
* The traversal uses `subtreeFlags` to skip every subtree with nothing to do.
* Children are handled before their parent.
*/
import { type Fiber, HostComponent, HostRoot, HostText, MutationMask, Placement, Update } from './fiber';
import { appendChild, commitUpdate, insertBefore, removeChild } from './dom-host';
export function commitMutationEffects(finishedWork: Fiber): void {
commitMutationEffectsOnFiber(finishedWork);
}
function recursivelyTraverseMutationEffects(parentFiber: Fiber): void {
// Deletions first. They are stored on the parent: a deleted fiber is not in the new tree.
const deletions = parentFiber.deletions;
if (deletions !== null) {
for (const childToDelete of deletions) commitDeletionEffects(parentFiber, childToDelete);
}
if (parentFiber.subtreeFlags & MutationMask) {
let child = parentFiber.child;
while (child !== null) {
commitMutationEffectsOnFiber(child);
child = child.sibling;
}
}
}
function commitMutationEffectsOnFiber(finishedWork: Fiber): void {
const current = finishedWork.alternate;
const flags = finishedWork.flags;
// Everything below this fiber first, then its own Placement, then its own Update.
recursivelyTraverseMutationEffects(finishedWork);
commitReconciliationEffects(finishedWork);
switch (finishedWork.tag) {
case HostComponent:
if (flags & Update) {
const updatePayload: string[] = finishedWork.updateQueue;
finishedWork.updateQueue = null;
commitUpdate(finishedWork.stateNode, updatePayload, current!.memoizedProps, finishedWork.memoizedProps);
}
return;
case HostText:
if (flags & Update) finishedWork.stateNode.nodeValue = finishedWork.memoizedProps;
return;
}
}
function commitReconciliationEffects(finishedWork: Fiber): void {
if (finishedWork.flags & Placement) {
commitPlacement(finishedWork);
// Done. Clear the bit so nothing takes this fiber for one that still has to be inserted.
finishedWork.flags &= ~Placement;
}
}
// ---------------------------------------------------------------------------
// Placement
// ---------------------------------------------------------------------------
function isHostParent(fiber: Fiber): boolean {
return fiber.tag === HostComponent || fiber.tag === HostRoot;
}
/** The nearest ancestor that has a DOM node: components and fragments have none. */
function getHostParentFiber(fiber: Fiber): Fiber {
let parent = fiber.return;
while (parent !== null) {
if (isHostParent(parent)) return parent;
parent = parent.return;
}
throw new Error('Expected to find a host parent.');
}
/**
* Find the DOM node we must insert BEFORE: the next host node to the right in
* the fiber tree that is already at its place, i.e. NOT flagged Placement itself.
* The search goes through siblings, down into components and fragments (they
* have no DOM node of their own) and up through parents that are not host nodes.
* null = nothing stable comes after us: append.
*/
function getHostSibling(fiber: Fiber): Node | null {
let node: Fiber = fiber;
siblings: while (true) {
// No sibling: climb. A host parent ends the search, nothing comes after us inside it.
while (node.sibling === null) {
if (node.return === null || isHostParent(node.return)) return null;
node = node.return;
}
node = node.sibling;
// Not a DOM node: look inside it for its first one.
while (node.tag !== HostComponent && node.tag !== HostText) {
if (node.flags & Placement) continue siblings; // it is being placed too: its nodes are not stable
if (node.child === null) continue siblings; // it renders nothing
node = node.child;
}
if (!(node.flags & Placement)) return node.stateNode;
}
}
function commitPlacement(finishedWork: Fiber): void {
const parentFiber = getHostParentFiber(finishedWork);
const parent: Node = parentFiber.tag === HostRoot ? parentFiber.stateNode.containerInfo : parentFiber.stateNode;
const before = getHostSibling(finishedWork);
insertOrAppendPlacementNode(finishedWork, before, parent);
}
function insertOrAppendPlacementNode(node: Fiber, before: Node | null, parent: Node): void {
if (node.tag === HostComponent || node.tag === HostText) {
if (before) insertBefore(parent, node.stateNode, before);
else appendChild(parent, node.stateNode);
return;
}
// A component or a fragment: insert each of its top-level host nodes.
let child = node.child;
while (child !== null) {
insertOrAppendPlacementNode(child, before, parent);
child = child.sibling;
}
}
// ---------------------------------------------------------------------------
// Deletion
// ---------------------------------------------------------------------------
/** The DOM node the deletion in progress removes from. */
let hostParent: Node | null = null;
function commitDeletionEffects(returnFiber: Fiber, deletedFiber: Fiber): void {
// `returnFiber` may be the host parent itself (a <ul> losing an <li>), so the search starts AT it.
const parentFiber = isHostParent(returnFiber) ? returnFiber : getHostParentFiber(returnFiber);
hostParent = parentFiber.tag === HostRoot ? parentFiber.stateNode.containerInfo : parentFiber.stateNode;
commitDeletionEffectsOnFiber(deletedFiber);
hostParent = null;
}
function recursivelyTraverseDeletionEffects(parent: Fiber): void {
let child = parent.child;
while (child !== null) {
commitDeletionEffectsOnFiber(child);
child = child.sibling;
}
}
function commitDeletionEffectsOnFiber(deletedFiber: Fiber): void {
switch (deletedFiber.tag) {
case HostComponent:
case HostText:
// One removal. Do NOT go below it: everything inside leaves the page with it.
if (hostParent !== null) removeChild(hostParent, deletedFiber.stateNode);
return;
default:
// A component or a fragment has no DOM node: its nodes are further down.
recursivelyTraverseDeletionEffects(deletedFiber);
}
}commitRoot becomes two steps: the mutation pass, then the swap of
root.current (the last step of the +1 commit above).
The new commitRoot in src/mini-react/work-loop.ts
The imports of work-loop.ts swap appendAllChildren for commitMutationEffects from ./commit-work:
// ---------------------------------------------------------------------------
// Commit phase
// ---------------------------------------------------------------------------
function commitRoot(root: FiberRoot): void {
// The tree the render phase just finished: the alternate of the tree on screen.
const finishedWork = root.current.alternate!;
// 1. Mutation: the only call in the library that changes what the user sees.
commitMutationEffects(finishedWork);
// 2. The swap: the work-in-progress tree is now the current tree.
root.current = finishedWork;
}The order matters. During the mutation pass current still means the old tree,
which is where the old props are read from. The pointer moves once the DOM
matches the new tree.
The one-line commit from First paint is now a special case. On the first render the
work-in-progress root already has a current (the empty root fiber from
createRoot), so App is reconciled in tracking mode and gets one Placement.
Everything below App is mounted without flags and built off-screen. The
commit finds one flag and appends one node.
The demo
There is no state yet, so the demo keeps a plain object outside React and every
button calls root.render() with a new version of it. A MutationObserver
writes what the document saw into a <pre> under the card. When a node is
removed and added again in the same batch, it prints one line: "moved". The
observer sees the page, not the calls: a listener swapped by commitUpdate
leaves no trace in the log.
The demo's code
/**
* DEMO — the reconciler
* =====================
*
* There is no state yet: every button calls root.render() again with different
* props. The box under the card lists what the DOCUMENT saw during that render.
*/
import { createRoot, walkLog } from 'mini-react';
interface State {
count: number;
items: string[];
keyed: boolean;
ordered: boolean;
}
let state: State = { count: 0, items: ['A', 'B', 'C', 'D'], keyed: true, ordered: false };
let nextLetter = 69; // 'E'
function Counter(props: { count: number }) {
return (
<p>
Count: {props.count} <button onClick={() => update({ count: props.count + 1 })}>+1</button>
</p>
);
}
function Row(props: { name: string }) {
return (
<li>
<b>{props.name}</b> <input placeholder="type here" />
</li>
);
}
function App(props: State) {
const { items, keyed, ordered } = props;
const List = ordered ? 'ol' : 'ul';
return (
<div className="card" style={{ width: 420, padding: 16, border: '1px solid gray', borderRadius: 8 }}>
<Counter count={props.count} />
<List>{items.map((name) => (keyed ? <Row key={name} name={name} /> : <Row name={name} />))}</List>
<p>
<button onClick={() => update({ items: [...items.slice(-1), ...items.slice(0, -1)] })}>last to front</button>
<button onClick={() => update({ items: [...items.slice(1), ...items.slice(0, 1)] })}>first to back</button>
<button onClick={() => update({ items: [String.fromCharCode(nextLetter++), ...items] })}>add to front</button>
<button onClick={() => update({ items: items.slice(1) })}>remove first</button>
<button onClick={() => update({ items: ['A', 'B', 'C', 'D'] })}>reset</button>
</p>
<p>
<button onClick={() => update({ keyed: !keyed })}>keys: {keyed ? 'on' : 'off'}</button>
<button onClick={() => update({ ordered: !ordered })}>list: {ordered ? 'ol' : 'ul'}</button>
</p>
</div>
);
}
const container = document.getElementById('root')!;
// The log lives OUTSIDE the container, so writing to it is not seen by the observer.
const log = document.createElement('pre');
document.body.append(log);
function show(node: Node): string {
if (node.nodeType === Node.TEXT_NODE) return `"${node.nodeValue}"`;
const text = node.textContent!.trim();
return `<${(node as Element).localName}> ${text.length > 10 ? text.slice(0, 10) + '…' : text}`;
}
// Everything the DOCUMENT sees happening inside the container, however deep.
new MutationObserver((records) => {
const lines: string[] = [];
const removedAt = new Map<Node, number>(); // node -> the index of its "removed" line
for (const record of records) {
if (record.type === 'characterData') lines.push(`text "${record.oldValue}" -> "${record.target.nodeValue}"`);
if (record.type === 'attributes') lines.push(`attribute ${record.attributeName} on ${show(record.target)}`);
for (const node of record.removedNodes) {
removedAt.set(node, lines.length);
lines.push(`removed ${show(node)}`);
}
for (const node of record.addedNodes) {
// Taken out and put back in during the same commit: the node MOVED.
const at = removedAt.get(node);
if (at === undefined) lines.push(`inserted ${show(node)}`);
else lines[at] = `moved ${show(node)}`;
}
}
log.textContent = `${lines.length} DOM operation(s)\n` + lines.map((line) => ` ${line}\n`).join('');
}).observe(container, {
childList: true,
subtree: true,
characterData: true,
characterDataOldValue: true,
attributes: true,
});
walkLog.enabled = false; // true prints every begin / complete
const root = createRoot(container);
function update(patch: Partial<State>) {
state = { ...state, ...patch };
log.textContent = '0 DOM operation(s)\n'; // the observer overwrites this if the document saw anything
root.render(<App {...state} />);
}
update({});Here is the demo running, click by click: the page's DOM nodes as two strips
(the counter's <p> and the list), what the log box printed, and the line of
the demo that each click runs:
The demo’s page as two strips of DOM nodes, and its log box. The counter’s p holds "Count: ", "1", " " and a button. The list is now an ol with three new li nodes, B, C and D. The log box printed 3 DOM operations: removed <ul> B C D, inserted <ol> B C D, and text "ul" -> "ol".
What the log box printed
1 DOM operation(s) inserted <div> Count: 0 +…1 DOM operation(s) text "0" -> "1"3 DOM operation(s) moved <li> A moved <li> B moved <li> C1 DOM operation(s) moved <li> D1 DOM operation(s) moved <li> A3 DOM operation(s) moved <li> B moved <li> C moved <li> D3 DOM operation(s) moved <li> A moved <li> B moved <li> C1 DOM operation(s) moved <li> D9 DOM operation(s) removed <li> A removed <li> B removed <li> C removed <li> D inserted <li> A inserted <li> B inserted <li> C inserted <li> D text "on" -> "off"4 DOM operation(s) text "A" -> "D" text "B" -> "A" text "C" -> "B" text "D" -> "C"3 DOM operation(s) removed <ul> B C D inserted <ol> B C D text "ul" -> "ol"Step 1 of 10
- The first
update({}). The page is empty, and the commit makes one call: the whole card goes in at once. The observer sees a single insert, thedivwith everything inside it. - A click on
+1. Every component is called again and more than fifty fibers are visited, but the document sees one write: the text node goes from"0"to"1". The same node, with new text. last to frontwith keys:[A,B,C,D] → [D,A,B,C]. A, B and C move and D is never touched: the three flags from Keyed diff, as real DOM moves. Eachliis the node it was before.resetputsA B C Dback. That is one move too, D back to the end. The next case starts from here.first to back:[B,C,D,A]. One move, A’s. Towards the back is the cheap direction.- Another
reset, from[B,C,D,A]: this time A stays and B, C and D move behind it, three moves. Then typehello Ainto row A’s input. React knows nothing about that: the text lives in the DOM node. last to frontagain. With keys, the text follows row A: theli, its input and what was typed are one subtree, and the subtree moved.reset(one move, as the first time), then switch the keys off and type into row A again. Switching them off changes every key, so no old row matches: the four oldliare removed, four new ones inserted, and the button’s label goes fromontooff. The first text left with the old rows.last to frontwithout keys. Nothing moves: the rows are matched by position, so React rewrites four letters and leaves every node in place. The input withhello Anow sits next to D. A key is not a performance hint; it tells React which row is which.- Finally, after
resetandremove first(B C D),list: ul. Same position, different type: one removal, one insert of anolbuilt off-screen, and the button’s label. The rows look the same, but they are new nodes: whatever was typed is gone.
Highlighted line: 106.
Highlighted line: 23.
Highlighted line: 44.
Highlighted line: 48.
Highlighted line: 45.
Highlighted lines: 31, 48.
Highlighted line: 44.
Highlighted lines: 48, 51.
Highlighted line: 44.
Highlighted line: 52.
/**
* DEMO — the reconciler
* =====================
*
* There is no state yet: every button calls root.render() again with different
* props. The box under the card lists what the DOCUMENT saw during that render.
*/
import { createRoot, walkLog } from 'mini-react';
interface State {
count: number;
items: string[];
keyed: boolean;
ordered: boolean;
}
let state: State = { count: 0, items: ['A', 'B', 'C', 'D'], keyed: true, ordered: false };
let nextLetter = 69; // 'E'
function Counter(props: { count: number }) {
return (
<p>
Count: {props.count} <button onClick={() => update({ count: props.count + 1 })}>+1</button>
</p>
);
}
function Row(props: { name: string }) {
return (
<li>
<b>{props.name}</b> <input placeholder="type here" />
</li>
);
}
function App(props: State) {
const { items, keyed, ordered } = props;
const List = ordered ? 'ol' : 'ul';
return (
<div className="card" style={{ width: 420, padding: 16, border: '1px solid gray', borderRadius: 8 }}>
<Counter count={props.count} />
<List>{items.map((name) => (keyed ? <Row key={name} name={name} /> : <Row name={name} />))}</List>
<p>
<button onClick={() => update({ items: [...items.slice(-1), ...items.slice(0, -1)] })}>last to front</button>
<button onClick={() => update({ items: [...items.slice(1), ...items.slice(0, 1)] })}>first to back</button>
<button onClick={() => update({ items: [String.fromCharCode(nextLetter++), ...items] })}>add to front</button>
<button onClick={() => update({ items: items.slice(1) })}>remove first</button>
<button onClick={() => update({ items: ['A', 'B', 'C', 'D'] })}>reset</button>
</p>
<p>
<button onClick={() => update({ keyed: !keyed })}>keys: {keyed ? 'on' : 'off'}</button>
<button onClick={() => update({ ordered: !ordered })}>list: {ordered ? 'ol' : 'ul'}</button>
</p>
</div>
);
}
const container = document.getElementById('root')!;
// The log lives OUTSIDE the container, so writing to it is not seen by the observer.
const log = document.createElement('pre');
document.body.append(log);
function show(node: Node): string {
if (node.nodeType === Node.TEXT_NODE) return `"${node.nodeValue}"`;
const text = node.textContent!.trim();
return `<${(node as Element).localName}> ${text.length > 10 ? text.slice(0, 10) + '…' : text}`;
}
// Everything the DOCUMENT sees happening inside the container, however deep.
new MutationObserver((records) => {
const lines: string[] = [];
const removedAt = new Map<Node, number>(); // node -> the index of its "removed" line
for (const record of records) {
if (record.type === 'characterData') lines.push(`text "${record.oldValue}" -> "${record.target.nodeValue}"`);
if (record.type === 'attributes') lines.push(`attribute ${record.attributeName} on ${show(record.target)}`);
for (const node of record.removedNodes) {
removedAt.set(node, lines.length);
lines.push(`removed ${show(node)}`);
}
for (const node of record.addedNodes) {
// Taken out and put back in during the same commit: the node MOVED.
const at = removedAt.get(node);
if (at === undefined) lines.push(`inserted ${show(node)}`);
else lines[at] = `moved ${show(node)}`;
}
}
log.textContent = `${lines.length} DOM operation(s)\n` + lines.map((line) => ` ${line}\n`).join('');
}).observe(container, {
childList: true,
subtree: true,
characterData: true,
characterDataOldValue: true,
attributes: true,
});
walkLog.enabled = false; // true prints every begin / complete
const root = createRoot(container);
function update(patch: Partial<State>) {
state = { ...state, ...patch };
log.textContent = '0 DOM operation(s)\n'; // the observer overwrites this if the document saw anything
root.render(<App {...state} />);
}
update({});More than fifty fibers are visited on every click and every component is
called, yet the document sees only what changed. The cliffhanger of
First paint is fixed, and the moves are the ones the table in
Keyed diff predicted. Without keys,
remove first removes the last <li> and renames the others. A key is not a
performance hint; it tells React which row is which.
What the log box printed, click by click
First paint:
1 DOM operation(s)
inserted <div> Count: 0 +…A click on +1:
1 DOM operation(s)
text "0" -> "1"last to front, [A,B,C,D] → [D,A,B,C], with keys:
3 DOM operation(s)
moved <li> A
moved <li> B
moved <li> Creset, back to [A,B,C,D]:
1 DOM operation(s)
moved <li> Dfirst to back, [B,C,D,A]:
1 DOM operation(s)
moved <li> Areset again, from [B,C,D,A]:
3 DOM operation(s)
moved <li> B
moved <li> C
moved <li> Dreset once more (the same one move as the first time), then keys: on, which switches them off:
9 DOM operation(s)
removed <li> A
removed <li> B
removed <li> C
removed <li> D
inserted <li> A
inserted <li> B
inserted <li> C
inserted <li> D
text "on" -> "off"With "hello A" typed into row A again, last to front without keys:
4 DOM operation(s)
text "A" -> "D"
text "B" -> "A"
text "C" -> "B"
text "D" -> "C"After reset and remove first, list: ul:
3 DOM operation(s)
removed <ul> B C D
inserted <ol> B C D
text "ul" -> "ol"What we simplified
- No bailout. Every component re-renders on every
root.render(). - No state, no hooks, no effects, no refs. The commit has a single pass. Because nothing needs cleaning up, a deleted DOM node is removed without visiting what is inside it.
- No update queue on the root, no scheduling.
render()writes the element into the root fiber and does all the work before it returns. - Events are still attached per node with
addEventListener. Updateonly when something changed. Real React flags a host fiber whenever its props object is new, so that delegated event handlers see the latest props. That comes back with the real event system.- Text is written with
nodeValuedirectly; real React goes through a host function for it.
Where this plugs in
This library is the trunk for the next milestone, Stateful React. Updates still come from
outside, by calling root.render() again, and they always start at the top.
The next three lessons build a component's own memory in isolation: the hooks
list in Hooks list, the update queue in Update queue, and the two combined in State engine. Then they meet this reconciler:
a setState will mark one fiber, the render will skip what did not change, and
this commit will apply the rest.