From JSX to pixels
Milestone: First paint
Lesson 4 of 249 min
In this lesson
So far in this course I have built three things that do not know about each other.
Elements & JSX turns JSX into plain objects, and nothing draws them.
Fiber tree walks a tree of fibers with a while loop, but I linked the fibers by hand and the walk
only printed lines. DOM host creates and updates DOM nodes, but I called every
function myself.
This lesson writes the glue. There is no new concept in it. At the end,
createRoot(container).render(<App />) puts a tree of function components on
the page, and we will have met the most important split in React: the render
phase, which builds everything in memory, and the commit phase, which
touches the page.
One question to keep in mind: the final demo has 31 DOM nodes. While they are being built, how many times does the page change?
The starting point
I copied the finished files of the three lessons into one folder, src/mini-react/:
- from Elements & JSX:
shared.ts,jsx-runtime.ts,jsx-dev-runtime.ts,index.ts; - from DOM host:
dom-host.ts, and itsshallowEqualhelper pasted at the bottom ofshared.ts; - from Fiber tree:
fiber.tsandwork-loop.ts.
In work-loop.ts I deleted the pause machinery (budget, shouldYield,
workLoopConcurrent, and getWorkInProgress, which only reported where the walk had stopped). It comes back much later, with a real clock. I also
changed its import from './fiber.ts' to './fiber': the Fiber tree lesson ran in Node,
here a bundler resolves imports. The hand-built tree and the recursive walk
stay behind.
What remains of the work loop is the cursor, the loop, and a beginWork and
completeWork that only log. Those two are what gets replaced.
The plan is a pipeline with three arrows. Step through it here; each of the next sections steps through one part of it, next to its code.
Step 1 of 4
- It starts with an element, the plain object JSX makes:
<App />. Nothing draws it yet. beginWorkturns elements into fibers: it reads each element’s type, calls the components and links the children they return.completeWorkturns each fiber that stands for a tag or a text into a DOM node. The nodes are built detached: nothing is on the page yet.commitRootputs the finished tree in the container. It is the only arrow that touches the page.
From an element to a fiber
An element has a type, a key and props. createFiber takes a tag,
props and a key. The only thing missing is the tag, and the type decides it.
At the bottom of fiber.ts (plus import type { Key, ReactElement } from './shared' at the top):
Step 1 of 6
createFiberFromElementunpacks the element: itstype,keyandpropsbecome the arguments ofcreateFiberFromTypeAndProps.- A function as the
typeis a component, so the tag isFunctionComponent. - A string is a DOM tag:
HostComponent. - Anything else is refused, the Fragment symbol included for now. There is no fiber to make, so it throws.
createFibermakes the fiber with that tag, the props and the key. The fiber keeps thetype: the tag name, or the function to call later.- A string between two tags is not an element, so it has its own function. Its
HostTextfiber keeps the string as its props.
Highlighted lines: 16 to 18.
Highlighted lines: 4 to 5.
Highlighted lines: 6 to 7.
Highlighted lines: 8 to 10.
Highlighted lines: 11 to 13.
Highlighted lines: 20 to 23.
// 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 {
throw new Error(`mini-react: unsupported element type: ${String(type)}`);
}
const fiber = createFiber(tag, pendingProps, key);
fiber.type = type;
return fiber;
}
export function createFiberFromElement(element: ReactElement): Fiber {
return createFiberFromTypeAndProps(element.type, element.key, element.props);
}
/** A string between two tags is not an element. Its fiber keeps the string as its "props". */
export function createFiberFromText(text: string): Fiber {
return createFiber(HostText, text, null);
}A function is a component, a string is a DOM tag, anything else is refused (including the Fragment symbol, for now). Text is not an element at all, so it has its own function.
From children to linked fibers
In the Fiber tree lesson I wrote the child, sibling and return pointers by hand. This
file writes them. Its input is a parent fiber and its children, which can be
one element, a string, a number, an array, or nothing.
Step 1 of 6
mountChildFibersgets a parent fiber and its children. An array goes toreconcileChildrenArray; anything else is one child.isElementreads the$$typeofsymbol from Elements & JSX. An element becomes a fiber throughcreateFiberFromElement.- A non-empty string or a number becomes a text fiber.
null,undefined, booleans and''make no fiber. That is why{isAdmin && <Button />}draws nothing whenisAdminis false.- Every new fiber points back to its parent with
return, the pointer the Fiber tree lesson wrote by hand. - For an array, flattened first, each child that makes a fiber is linked to the one before with
sibling. The first one is returned and becomes the parent’schild. Grandchildren wait for their ownbeginWork.
Highlighted lines: 36 to 39.
Highlighted lines: 4 to 6, 15.
Highlighted lines: 7 to 9, 14.
Highlighted line: 16.
Highlighted lines: 17 to 18.
Highlighted lines: 22 to 34.
import { type Fiber, createFiberFromElement, createFiberFromText } from './fiber';
import { REACT_ELEMENT_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';
}
/** One child -> one 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 return null; // null, undefined, true, false, ''
created.return = returnFiber;
return created;
}
/** Many children -> a chain of fibers. Returns the first one. */
function reconcileChildrenArray(returnFiber: Fiber, newChildren: any[]): Fiber | null {
let resultingFirstChild: Fiber | null = null;
let previousNewFiber: Fiber | null = null;
// `<ul><li/>{items.map(...)}</ul>` puts an array inside the array: flatten it.
for (const newChild of newChildren.flat(Infinity)) {
const newFiber = createChild(returnFiber, newChild);
if (newFiber === null) continue;
if (previousNewFiber === null) resultingFirstChild = newFiber;
else previousNewFiber.sibling = newFiber;
previousNewFiber = newFiber;
}
return resultingFirstChild;
}
export function mountChildFibers(returnFiber: Fiber, newChild: any): Fiber | null {
if (Array.isArray(newChild)) return reconcileChildrenArray(returnFiber, newChild);
return createChild(returnFiber, newChild);
}isElement is the first code that reads the $$typeof symbol from Elements & JSX.
createChild returns null for null, undefined and booleans, which is why
{isAdmin && <Button />} draws nothing when isAdmin is false. "Reconcile"
means comparing two things; on a first render there is nothing to compare with,
so this version only creates. Note that it builds one level and never looks at
grandchildren.
The real beginWork
The Fiber tree lesson's beginWork returned fiber.child, which already existed. Now it
has to create the children first, and what the children are depends on the tag.
Step 1 of 6
beginWorkgets the fiber under the cursor and switches on its tag: what its children are depends on it.- For the root, the children are the element given to
render, kept in the fiber’smemoizedState. - For a component, the children are what the function returns.
Component(nextProps)is the line that finally callsApp. - For a
div, the children areprops.children: they are elements already. reconcileChildrenturns them into fibers withmountChildFibersand hangs the first onchild.beginWorkreturns it, and the walk goes one level down.- A text fiber has no children:
beginWorkreturnsnull, and the walk turns around tocompleteWork.
Highlighted lines: 4 to 5.
Highlighted lines: 8 to 9, 30 to 34.
Highlighted lines: 6 to 7, 23 to 28.
Highlighted lines: 10 to 12.
Highlighted lines: 19 to 21.
Highlighted lines: 13 to 14.
import { type Fiber, FunctionComponent, HostComponent, HostRoot, HostText } from './fiber';
import { mountChildFibers } from './child-fiber';
export function beginWork(workInProgress: Fiber): Fiber | null {
switch (workInProgress.tag) {
case FunctionComponent:
return updateFunctionComponent(workInProgress, workInProgress.type, workInProgress.pendingProps);
case HostRoot:
return updateHostRoot(workInProgress);
case HostComponent:
reconcileChildren(workInProgress, workInProgress.pendingProps.children);
return workInProgress.child;
case HostText:
return null; // leaf
}
throw new Error(`Unknown fiber tag ${workInProgress.tag}`);
}
export function reconcileChildren(workInProgress: Fiber, nextChildren: any): void {
workInProgress.child = mountChildFibers(workInProgress, nextChildren);
}
function updateFunctionComponent(workInProgress: Fiber, Component: (props: any) => any, nextProps: any): Fiber | null {
// This is the line that calls your component.
const nextChildren = Component(nextProps);
reconcileChildren(workInProgress, nextChildren);
return workInProgress.child;
}
function updateHostRoot(workInProgress: Fiber): Fiber | null {
const nextChildren = workInProgress.memoizedState.element;
reconcileChildren(workInProgress, nextChildren);
return workInProgress.child;
}For a div, the children are props.children. For a component, the children
are whatever the function returns. In Elements & JSX a counter showed that writing
<Greeting /> calls nothing; Component(nextProps) is the line that finally
does. It is a plain call because there are no hooks yet. For the root, the
children are the element given to render, read from the fiber's state.
The consequence: the fiber tree is no longer built before the walk. It is built
by the walk, one level per beginWork.
The root and render()
A fiber does not know which DOM node to render into. That is the job of a
second object, the FiberRoot:
import { type Fiber, HostRoot, createFiber } from './fiber';
export interface FiberRoot {
/** The DOM node we render into. */
containerInfo: HTMLElement;
/** The HostRoot fiber: the top of this root's fiber tree. */
current: Fiber;
}
export function createFiberRoot(containerInfo: HTMLElement): FiberRoot {
const uninitializedFiber = createFiber(HostRoot, null, null);
const root: FiberRoot = { containerInfo, current: uninitializedFiber };
uninitializedFiber.stateNode = root;
uninitializedFiber.memoizedState = { element: null };
return root;
}The Fiber class in fiber.ts gets one new field for this, next to pendingProps:
/** The fiber's own state. Only the HostRoot has one so far: { element }, what render() was given. */
memoizedState: any = null;And the public entry point:
import { createFiberRoot } from './fiber-root';
import { performSyncWorkOnRoot } from './work-loop';
export interface Root {
render(element: any): void;
}
export function createRoot(container: HTMLElement): Root {
const root = createFiberRoot(container);
const updateContainer = (element: any) => {
const hostRootFiber = root.current;
// The HostRoot's state is "the element I was asked to render".
// updateHostRoot (begin-work.ts) reads it back.
hostRootFiber.memoizedState = { element };
performSyncWorkOnRoot(root);
};
return { render: updateContainer };
}render stores the element where updateHostRoot reads it, then does all the
work before returning. index.ts gains export { createRoot, type Root } from './root'.
completeWork makes DOM nodes
The Fiber tree lesson had a rule: a fiber completes only after all its children have
completed. That makes completeWork the right place to create DOM nodes. When a
div completes, its children's nodes already exist, so it can create itself and
put them inside.
Step 1 of 6
- The deepest fibers complete first. A text fiber gets a text node, kept in its
stateNode. - When
h1completes,createInstancemakes the element: the whole DOM host lesson in one call. - Its children completed earlier, so their nodes exist.
appendAllChildrenputs them inside, without going into them. - The fiber keeps its node in
stateNode, where its parent will look for it. Countercompletes too, but a component has no DOM node of its own, and neither has the root.- When
divcompletes, the walk goes down throughCounterto append itsp, then climbs back and moves on tofooter. The tree is built, still detached.
Highlighted lines: 18 to 20.
Highlighted lines: 11 to 12.
Highlighted lines: 13, 26 to 31.
Highlighted lines: 14 to 15.
Highlighted lines: 7 to 9.
Highlighted lines: 32 to 42.
import { type Fiber, FunctionComponent, HostComponent, HostRoot, HostText } from './fiber';
import { createInstance, createTextInstance, appendChild } from './dom-host';
export function completeWork(workInProgress: Fiber): void {
const newProps = workInProgress.pendingProps;
switch (workInProgress.tag) {
case FunctionComponent:
case HostRoot:
return; // no DOM node of their own
case HostComponent: {
const instance = createInstance(workInProgress.type, newProps);
appendAllChildren(instance, workInProgress);
workInProgress.stateNode = instance;
return;
}
case HostText:
workInProgress.stateNode = createTextInstance(newProps);
return;
}
throw new Error(`Unknown fiber tag ${workInProgress.tag}`);
}
/** Append the top-level host nodes of the subtree (skipping components). */
export function appendAllChildren(parent: HTMLElement, workInProgress: Fiber): void {
let node = workInProgress.child;
while (node !== null) {
if (node.tag === HostComponent || node.tag === HostText) {
// A DOM node: append it. Do NOT go below it, its own children are already inside.
appendChild(parent, node.stateNode);
} else if (node.child !== null) {
// A component: it has no DOM node. Its DOM nodes are further down.
node = node.child;
continue;
}
// Next: the sibling, or the sibling of the nearest ancestor that has one.
while (node.sibling === null) {
if (node.return === null || node.return === workInProgress) return;
node = node.return;
}
node = node.sibling;
}
}createInstance is the whole of the DOM host lesson in one call: className, styles,
the temporary click listener. appendAllChildren cannot simply loop over the
child fibers, because a child may be a component, and a component has no DOM
node. Its nodes are further down, so the function walks: append host nodes
without going inside them, go down through components, then move to the sibling
or climb return until there is one.
The work loop, and commitRoot
Here is work-loop.ts after the edits. The two logging functions are gone
(their console.log lines moved into the loop, behind a flag), the loop starts
from a FiberRoot, and there is one new function at the bottom.
Step 1 of 5
performSyncWorkOnRootis two lines, and they are the two phases: render, in memory, then commit.- The render phase points the cursor at the root fiber and loops until the cursor is
null. - Each unit of work is a
beginWork. When it returns a child, the cursor moves down; when it returnsnull, the fiber completes. completeUnitOfWorkrunscompleteWork, then moves to the sibling, or climbs to the parent and completes it too. At the end the cursor isnulland the DOM tree exists, detached.commitRootappends the finished tree to the container withappendAllChildren: one change to the document, and the page shows it.
Highlighted lines: 12 to 15.
Highlighted lines: 17 to 29.
Highlighted lines: 31 to 36.
Highlighted lines: 39 to 52.
Highlighted lines: 54 to 58.
import { getFiberName, type Fiber } from './fiber';
import type { FiberRoot } from './fiber-root';
import { beginWork } from './begin-work';
import { appendAllChildren, completeWork } from './complete-work';
/** LESSON ONLY: set `enabled` to print the walk, the same lines the Fiber tree lesson printed. */
export const walkLog = { enabled: false };
/** The cursor: the fiber we are about to work on. null = nothing left to do. */
let workInProgress: Fiber | null = null;
export function performSyncWorkOnRoot(root: FiberRoot): void {
renderRootSync(root);
commitRoot(root);
}
function renderRootSync(root: FiberRoot): void {
prepareFreshStack(root);
workLoopSync();
}
/** Start a walk: point the cursor at the top of a tree. */
export function prepareFreshStack(root: FiberRoot): void {
workInProgress = root.current;
}
export function workLoopSync(): void {
while (workInProgress !== null) performUnitOfWork(workInProgress);
}
function performUnitOfWork(unitOfWork: Fiber): void {
if (walkLog.enabled) console.log(`begin ${getFiberName(unitOfWork)}`);
const next = beginWork(unitOfWork);
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 {
if (walkLog.enabled) console.log(`complete ${getFiberName(completedWork)}`);
completeWork(completedWork);
const sibling: Fiber | null = completedWork.sibling;
if (sibling !== null) {
workInProgress = sibling;
return;
}
completedWork = completedWork.return;
workInProgress = completedWork;
} while (completedWork !== null);
}
function commitRoot(root: FiberRoot): void {
const finishedWork = root.current;
// The only line in the library that changes what the user sees.
appendAllChildren(root.containerInfo, finishedWork);
}performSyncWorkOnRoot is two lines, and they are the two phases. If you leave
out the commitRoot(root) call and run a demo, the walk runs, every DOM node is
created, and the page stays blank: the top div exists in memory with all its
children, but it has no parent. commitRoot gives it one. It reuses
appendAllChildren, this time with the real container as the parent.
index.ts also exports walkLog, a lesson-only switch.
The demo
The diagrams above take one function at a time. Here they run together: one walk over a small tree, a check of when the page changes, and a bigger app that leads into what this version cannot do.
First, the tree from the Fiber tree lesson, written as components:
function Counter() {
return <p>Count: 0</p>;
}
function App() {
return (
<div>
<h1>Hello</h1>
<Counter />
<footer />
</div>
);
}
walkLog.enabled = true;
createRoot(document.getElementById('root')!).render(<App />);What it prints
begin HostRoot
begin App
begin div
begin h1
begin #text
complete #text
complete h1
begin Counter
begin p
begin #text
complete #text
complete p
complete Counter
begin footer
complete footer
complete div
complete App
complete HostRootIt prints 18 lines. Step through them below: each step prints a few and shows what they did to the fibers, the detached DOM and the container.
After the walk: workInProgress is null and nothing is detached any more, because the finished div with its h1, p and footer was appended to the container in one commit, so container.children holds that div. The log shows all 18 lines of the walk.
Variables
- workInProgress
- null
- detachedTrees
- []
- container.children
- [<div>]
Log
begin HostRootbegin Appbegin divbegin h1begin #textcomplete #textcomplete h1begin Counterbegin pbegin #textcomplete #textcomplete pcomplete Counterbegin footercomplete footercomplete divcomplete Appcomplete HostRootStep 1 of 7
- From
begin HostRoottobegin #textno fiber existed beforehand: eachbeginWorkcreates the children of the fiber it is on.updateHostRootmakesAppfrom the element given torender,updateFunctionComponentcallsApp(props)and makes thedivfrom what it returns, thedivmakesh1,Counterandfooterin one go (the walk only beginsh1next), andh1makes its text. Real React reconciles here too, with keys, moves and bailouts in the way; this version only creates. #texthas nothing below it, sobeginWorkreturnsnulland the walk turns around.completeWorkcallscreateTextInstance: a text nodeHelloexists, with no parent.detachedTreeslists the DOM built so far that has no parent yet; the page has not changed.#texthas no sibling, socompleteUnitOfWorkclimbs to its parent and completesh1.createInstancemakes the element,appendAllChildrenputs the text node inside it andstateNodekeeps it. A whole subtree exists in memory, attached to nothing.h1does have a sibling,Counter, so the walk goes there next.Counteris the next sibling, so the walk goes down again:updateFunctionComponentcallsCounter(), it returns ap, and thepgets its text.complete pbuilds<p>Count: 0</p>, butcomplete Counterbuilds nothing: a function component has no DOM node, socompleteWorkjust returns. Two detached subtrees now.footerbegins and completes in one go, thendivcompletes.createInstancemakes it andappendAllChildrencollects its DOM children: theh1, thenCounter, which is a component, so the walk goes down through it and appends itsp, thenfooter. This is how thepreaches thedivacross the function fiber.AppandHostRootcomplete and create nothing: neither has a DOM node. The cursor isnull, the render phase is over, and the whole page is one detacheddiv. The document has not seen a single change.commitRootcallsappendAllChildrenagain, now with the real container as the parent: it walks down throughAppand appends thediv. One insertion, which is why theMutationObserverprintsthe document saw 1 change(s)andadded <div> with 3 elements inside. React also builds the DOM incompleteWorkand inserts it once at commit, but it marks the top fiber for placement during render and its commit phase does the insert, instead of appending the root's DOM children.
Highlighted lines: 3 to 9, 16 to 18.
Highlighted lines: 10 to 11.
Highlighted lines: 3 to 4.
export function beginWork(workInProgress: Fiber): Fiber | null {
switch (workInProgress.tag) {
case FunctionComponent:
return updateFunctionComponent(workInProgress, workInProgress.type, workInProgress.pendingProps);
case HostRoot:
return updateHostRoot(workInProgress);
case HostComponent:
reconcileChildren(workInProgress, workInProgress.pendingProps.children);
return workInProgress.child;
case HostText:
return null; // leaf
}
throw new Error(`Unknown fiber tag ${workInProgress.tag}`);
}
export function reconcileChildren(workInProgress: Fiber, nextChildren: any): void {
workInProgress.child = mountChildFibers(workInProgress, nextChildren);
}Highlighted lines: 3 to 5.
Highlighted lines: 3 to 5.
function updateFunctionComponent(workInProgress: Fiber, Component: (props: any) => any, nextProps: any): Fiber | null {
// This is the line that calls your component.
const nextChildren = Component(nextProps);
reconcileChildren(workInProgress, nextChildren);
return workInProgress.child;
}
function updateHostRoot(workInProgress: Fiber): Fiber | null {
const nextChildren = workInProgress.memoizedState.element;
reconcileChildren(workInProgress, nextChildren);
return workInProgress.child;
}Highlighted lines: 4 to 5, 7 to 8.
/** One child -> one 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 return null; // null, undefined, true, false, ''
created.return = returnFiber;
return created;
}export function mountChildFibers(returnFiber: Fiber, newChild: any): Fiber | null {
if (Array.isArray(newChild)) return reconcileChildrenArray(returnFiber, newChild);
return createChild(returnFiber, newChild);
}Highlighted lines: 15 to 17.
Highlighted lines: 8 to 13.
Highlighted lines: 4 to 6, 8 to 13.
Highlighted lines: 8 to 13.
Highlighted lines: 4 to 6.
export function completeWork(workInProgress: Fiber): void {
const newProps = workInProgress.pendingProps;
switch (workInProgress.tag) {
case FunctionComponent:
case HostRoot:
return; // no DOM node of their own
case HostComponent: {
const instance = createInstance(workInProgress.type, newProps);
appendAllChildren(instance, workInProgress);
workInProgress.stateNode = instance;
return;
}
case HostText:
workInProgress.stateNode = createTextInstance(newProps);
return;
}
throw new Error(`Unknown fiber tag ${workInProgress.tag}`);
}Highlighted lines: 3 to 7, 13 to 18.
Highlighted lines: 2 to 11, 13 to 18.
Highlighted lines: 2 to 11.
/** Append the top-level host nodes of the subtree (skipping components). */
export function appendAllChildren(parent: HTMLElement, workInProgress: Fiber): void {
let node = workInProgress.child;
while (node !== null) {
if (node.tag === HostComponent || node.tag === HostText) {
// A DOM node: append it. Do NOT go below it, its own children are already inside.
appendChild(parent, node.stateNode);
} else if (node.child !== null) {
// A component: it has no DOM node. Its DOM nodes are further down.
node = node.child;
continue;
}
// Next: the sibling, or the sibling of the nearest ancestor that has one.
while (node.sibling === null) {
if (node.return === null || node.return === workInProgress) return;
node = node.return;
}
node = node.sibling;
}
}Highlighted lines: 2 to 5.
Highlighted lines: 12 to 13, 19 to 21.
Highlighted lines: 19 to 21.
function performUnitOfWork(unitOfWork: Fiber): void {
if (walkLog.enabled) console.log(`begin ${getFiberName(unitOfWork)}`);
const next = beginWork(unitOfWork);
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 {
if (walkLog.enabled) console.log(`complete ${getFiberName(completedWork)}`);
completeWork(completedWork);
const sibling: Fiber | null = completedWork.sibling;
if (sibling !== null) {
workInProgress = sibling;
return;
}
completedWork = completedWork.return;
workInProgress = completedWork;
} while (completedWork !== null);
}Highlighted lines: 3 to 4.
function commitRoot(root: FiberRoot): void {
const finishedWork = root.current;
// The only line in the library that changes what the user sees.
appendAllChildren(root.containerInfo, finishedWork);
}It is the order from the Fiber tree lesson, line for line, with four new lines in the
middle: Counter is now really called, so the walk goes into the <p> it returned.
Now the question from the top. I put a MutationObserver on the container
before rendering. With subtree: true it reports every node added anywhere
below the container.
new MutationObserver((records) => {
console.log(`the document saw ${records.length} change(s)`);
for (const record of records) {
for (const node of record.addedNodes) {
const el = node as HTMLElement;
console.log(` added <${el.localName}> with ${el.querySelectorAll('*').length} elements inside`);
}
}
}).observe(container, { childList: true, subtree: true });the document saw 1 change(s)
added <div> with 3 elements insideEighteen lines of render phase, during which the document saw nothing, then one change. The page never shows a half-built tree, because a half-built tree is never in the document.
The final demo is closer to real code: props, a .map list of components, text
mixed with elements, className, style, and a button.
The demo’s code
import { createRoot, walkLog } from 'mini-react';
const PIECES = [
{ id: 1, name: 'JSX makes elements' },
{ id: 2, name: 'beginWork makes fibers' },
{ id: 3, name: 'completeWork makes DOM nodes' },
];
function Piece(props: { id: number; name: string }) {
return (
<li className="piece">
<b>0{props.id}</b> {props.name}
</li>
);
}
function Counter(props: { count: number }) {
return (
<p>
Count: {props.count} <button onClick={() => render(props.count + 1)}>+1</button>
</p>
);
}
function App(props: { name: string; count: number }) {
return (
<div className="card" style={{ width: 320, padding: 16, border: '1px solid gray', borderRadius: 8 }}>
<h1>Hello, {props.name}</h1>
<ul>
{PIECES.map((piece) => (
<Piece key={piece.id} id={piece.id} name={piece.name} />
))}
</ul>
<Counter count={props.count} />
<footer style={{ color: 'gray', fontSize: 12 }}>painted by mini-react</footer>
</div>
);
}
const container = document.getElementById('root')!;
// ...the MutationObserver from above goes here...
walkLog.enabled = false; // true prints every begin / complete
const root = createRoot(container);
function render(count: number) {
root.render(<App name="Ada" count={count} />);
}
render(0);No code was written for lists, props or styles, and it works: 37 fibers, 31 DOM nodes, and the console says
the document saw 1 change(s)
added <div> with 11 elements insideWhat goes wrong
Look at the demo’s +1 button. There is no state in this library, so the only way to show
a different count is to call render again with new props. Click +1 and you
do not get "Count: 1" in place. You get a second card under the first one.
Click again, a third.
The second render did exactly what the first did: it called every component,
created 36 new fibers and 31 new DOM nodes for a one-character change, and
appended the result. Nothing removed the old card, because nothing remembers
there was one. The old button is still there too, still holding count = 0.
This React can paint. It cannot repaint.
What we simplified
render()writes the element straight into the root fiber'smemoizedState. Real React queues it as an update; the place it ends up is the same.- Everything is synchronous. There is no scheduler.
- Keys are stored on fibers and never read. Nested arrays are flattened. Fragments throw.
- Events still use the direct
addEventListenershortcut from the DOM host lesson. walkLogexists only so the walk can be printed.
Where this goes
To repaint, React has to compare the children it rendered last time with the
ones it wants now, and decide which nodes stay, which move and which go. The
next lesson, Keyed diff, builds that comparison alone, with no DOM. The
Reconciler milestone then merges it into this folder, and calling render twice will do
what you expect.