From JSX to pixels
Fiber tree
Lesson 2 of 248 min
In this lesson
React can stop rendering in the middle of your component tree, let the browser handle a click, and continue from the component where it stopped. JavaScript has no way to freeze a function that is halfway through a recursion and come back to it later. So something else must be going on.
It is not a clever algorithm. It is a data structure, the fiber, and in this lesson I build it from nothing: about a hundred lines, no dependencies, running in a terminal.
The walk everyone writes first
A UI is a tree, so the obvious representation is a node with an array of children, and the obvious way to visit it is recursion. The walk itself, from src/recursive.ts:
export function walk(node: TreeNode): void {
console.log(`begin ${node.name}`);
for (const child of node.children) walk(child);
console.log(`complete ${node.name}`);
}
walk(tree);TreeNode is just { name, children }, and tree is a small UI written out as nested objects: HostRoot, then App, then a div holding an h1 (with a text inside), a Counter and a footer.
Full src/recursive.ts
type TreeNode = { name: string; children: TreeNode[] };
const tree: TreeNode = {
name: 'HostRoot',
children: [
{
name: 'App',
children: [
{
name: 'div',
children: [
{ name: 'h1', children: [{ name: '#text', children: [] }] },
{ name: 'Counter', children: [] },
{ name: 'footer', children: [] },
],
},
],
},
],
};
export function walk(node: TreeNode): void {
console.log(`begin ${node.name}`);
for (const child of node.children) walk(child);
console.log(`complete ${node.name}`);
}
walk(tree);Step through it to see what it prints, one line at a time, and where the recursion is at each moment:
Step 1 of 11
walk(tree)iswalk(HostRoot): one frame on the call stack. It printsbegin HostRoot, and itsforloop is about to call the first child.- The loop calls
walk(App). A second frame goes on the stack, and it printsbegin App. The frame under it remembers that it is onchild 1/1. walk(div): a third frame, andbegin div.divhas three children; its loop starts with the first,h1.walk(h1)printsbegin h1. Four calls deep, and every frame under the top one is waiting inside itsforloop.walk(#text)printsbegin #text, has no children, printscomplete #textand returns. Its frame is gone, andwalk(h1)is on top again.- The loop in
walk(h1)has no more children, so it printscomplete h1and returns.walk(div)is on top, still onchild 1/3: the only record thatCountercomes next. - The loop in
walk(div)moves on tochild 2/3and callswalk(Counter):begin Counter, no children,complete Counter. - Then
child 3/3:walk(footer)begins and completes the same way. - The loop in
walk(div)is done:complete div, and the call returns towalk(App). complete App. One frame left.complete HostRoot, andwalk(HostRoot)returns. The stack is empty and all fourteen lines are printed. Every node completed only after all of its children.
Highlighted lines: 2, 7.
Highlighted lines: 2 to 3.
Highlighted lines: 2 to 3.
Highlighted lines: 2 to 3.
Highlighted lines: 2 to 4.
Highlighted lines: 3 to 4.
Highlighted lines: 2 to 4.
Highlighted lines: 2 to 4.
Highlighted lines: 3 to 4.
Highlighted lines: 3 to 4.
Highlighted lines: 3 to 4.
export function walk(node: TreeNode): void {
console.log(`begin ${node.name}`);
for (const child of node.children) walk(child);
console.log(`complete ${node.name}`);
}
walk(tree);"Begin" on the way down, "complete" on the way up. A node completes only after all of its children have completed. Those two words are React's own names for the two halves of visiting a node.
Now suppose the tree has ten thousand nodes and the user clicks while I am in the middle. I want to stop right after complete h1, handle the click, and carry on with Counter afterwards. Where does the pause go?
At that moment I am inside the for loop of div, inside walk(App), inside walk(HostRoot). My position in the tree is the call stack: a pile of half-finished calls, each remembering which child it was on. I cannot save a call stack and come back to it. If I return, it is gone. React worked this way up to version 15, which is why a large render could freeze the page.
The position has to live somewhere else: in data I control.
A node with three pointers
The fix is to put enough pointers in every node that I can find my way from any node with no memory at all. That node is a fiber.
The part of the class in src/fiber.ts that makes a tree:
export class Fiber {
// ...
// --- tree ---
return: Fiber | null = null;
child: Fiber | null = null;
sibling: Fiber | null = null;
// ...
}Full src/fiber.ts
// Work tags: "what kind of fiber is this?" (same numbers as real React)
export const FunctionComponent = 0;
export const HostRoot = 3; // the top of the tree
export const HostComponent = 5; // a DOM element: 'div', 'button', ...
export const HostText = 6; // a DOM text node
export type WorkTag = number;
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 (later: the DOM node). Unused for now. */
stateNode: any = null;
// --- tree ---
return: Fiber | null = null;
child: Fiber | null = null;
sibling: Fiber | null = null;
// --- inputs ---
/** Props for the render that is about to happen. For a text fiber: the string. */
pendingProps: any;
constructor(tag: WorkTag, pendingProps: any, key: string | null) {
this.tag = tag;
this.pendingProps = pendingProps;
this.key = key;
}
}
export function createFiber(tag: WorkTag, pendingProps: any, key: string | null): Fiber {
return new Fiber(tag, pendingProps, key);
}
export function getFiberName(fiber: Fiber): string {
switch (fiber.tag) {
case FunctionComponent:
return fiber.type.name;
case HostComponent:
return fiber.type;
case HostText:
return '#text';
case HostRoot:
return 'HostRoot';
default:
return 'Unknown';
}
}There is no children array. There is child, singular: the first child. The other children are reached through sibling. And return points at the parent.
The full file has a few more fields, which say what the fiber stands for rather than where it is. tag is the kind of fiber: a function component, a DOM element (a "host" component, the DOM being the host React renders into), a text node, or the single root at the top, with the numbers React uses. type is the component function or the string 'div', key is the key you put on list items, and pendingProps holds the props the fiber is about to render with. stateNode will hold the DOM node in a later lesson. The walk needs none of them; only getFiberName reads tag and type, to print a name.
Linking a tree by hand
React normally builds fibers from JSX. Nothing builds them for me yet, so I set every pointer myself, for this UI:
<App>
<div>
<h1>Hello</h1>
<Counter />
<footer />
</div>
</App>A function in src/tree.ts, buildTree, creates the seven fibers and then links them, one line per parent and child. Step through the linking, with the line that draws each arrow highlighted next to the tree:
Step 1 of 8
buildTreecreates the seven fibers and gives the components and elements theirtype. Nothing points anywhere yet: everychild,siblingandreturnis null.hostRoot.child = appdraws the solid arrow down, andapp.return = hostRootthe dashed one back up.- The same for
Appand its only child,div. div.child = h1:divhas three children, but only the first gets thechildarrow.h1.returnpoints back atdiv.h1.child = textandtext.return = h1. The way down is complete.h1.sibling = counterhangsCounteroffh1, sideways. Itsreturnskipsh1and points atdiv, its parent.counter.sibling = footer, andfooter.returnisdivtoo.- The tree is linked.
divhas one arrow going down and three coming back up;Counterandfooterare reached only throughsibling.buildTreereturnshostRoot.
Highlighted line: 2.
Highlighted line: 3.
Highlighted line: 4.
Highlighted line: 5.
Highlighted line: 8.
Highlighted line: 9.
Highlighted lines: 2 to 5, 8 to 9.
// Down: a parent points at its FIRST child only. Up: every child points at its parent.
hostRoot.child = app; app.return = hostRoot;
app.child = div; div.return = app;
div.child = h1; h1.return = div;
h1.child = text; text.return = h1;
// Sideways: the other children of <div> hang off the first one.
h1.sibling = counter; counter.return = div;
counter.sibling = footer; footer.return = div;Before linking, buildTree creates the fibers with createFiber and sets each type: the App and Counter functions for the components, 'div', 'h1' and 'footer' for the elements, and the string 'Hello' as the text fiber's props. The whole function is the dynamic way to build the same tree, the job JSX will take over later:
Full src/tree.ts
import { createFiber, FunctionComponent, HostComponent, HostRoot, HostText, type Fiber } from './fiber.ts';
// Never called in this lesson. A component fiber just needs a function to point at.
function App() {}
function Counter() {}
export function buildTree(): Fiber {
const hostRoot = createFiber(HostRoot, null, null);
const app = createFiber(FunctionComponent, {}, null);
app.type = App;
const div = createFiber(HostComponent, {}, null);
div.type = 'div';
const h1 = createFiber(HostComponent, {}, null);
h1.type = 'h1';
const text = createFiber(HostText, 'Hello', null);
const counter = createFiber(FunctionComponent, {}, null);
counter.type = Counter;
const footer = createFiber(HostComponent, {}, null);
footer.type = 'footer';
// Down: a parent points at its FIRST child only. Up: every child points at its parent.
hostRoot.child = app; app.return = hostRoot;
app.child = div; div.return = app;
div.child = h1; h1.return = div;
h1.child = text; text.return = h1;
// Sideways: the other children of <div> hang off the first one.
h1.sibling = counter; counter.return = div;
counter.sibling = footer; footer.return = div;
return hostRoot;
}div has three children but only one arrow going down. Counter and footer are nobody's child; the only way to reach them is through h1.sibling. Their return still points at div, so three arrows come back up to it.
Why "return" and not "parent"? Because it is where you go back to when you are done with a fiber, like the return address of a function call. That is exactly how the walk uses it.
One cursor and a while loop
The heart of src/work-loop.ts, the cursor and the loop that moves it:
/** The cursor: the fiber we are about to work on. null = nothing left to do. */
let workInProgress: Fiber | null = null;
/** Start a walk: point the cursor at the top of a tree. */
export function prepareFreshStack(root: Fiber): void {
workInProgress = root;
}
export function workLoopSync(): void {
while (workInProgress !== null) performUnitOfWork(workInProgress);
}
function performUnitOfWork(unitOfWork: Fiber): void {
const next = beginWork(unitOfWork);
if (next === null) completeUnitOfWork(unitOfWork);
else workInProgress = next;
}beginWork logs begin and returns fiber.child. completeUnitOfWork is the interesting one; the diagram below walks through it, and the full file is right after.
Full src/work-loop.ts
import { getFiberName, type Fiber } from './fiber.ts';
/** The cursor: the fiber we are about to work on. null = nothing left to do. */
let workInProgress: Fiber | null = null;
/** Start a walk: point the cursor at the top of a tree. */
export function prepareFreshStack(root: Fiber): void {
workInProgress = root;
}
export function workLoopSync(): void {
while (workInProgress !== null) performUnitOfWork(workInProgress);
}
function performUnitOfWork(unitOfWork: Fiber): void {
const next = beginWork(unitOfWork);
if (next === null) completeUnitOfWork(unitOfWork);
else workInProgress = next;
}
/** On the way DOWN. Returns the next fiber to work on: the first child, or null. */
function beginWork(fiber: Fiber): Fiber | null {
console.log(`begin ${getFiberName(fiber)}`);
return fiber.child;
}
/** Complete this fiber, then move to its sibling, or complete the parent. */
function completeUnitOfWork(unitOfWork: Fiber): void {
let completedWork: Fiber | null = unitOfWork;
do {
completeWork(completedWork);
const sibling: Fiber | null = completedWork.sibling;
if (sibling !== null) {
workInProgress = sibling;
return;
}
completedWork = completedWork.return;
workInProgress = completedWork;
} while (completedWork !== null);
}
/** On the way UP. Runs once everything below this fiber is done. */
function completeWork(fiber: Fiber): void {
console.log(`complete ${getFiberName(fiber)}`);
}The position is one variable, workInProgress. The loop runs while there is a fiber under it.
One unit of work begins a fiber. beginWork answers "where next?" with the first child. If there is one, the cursor moves down and the unit is over. If there is none, the fiber is complete, and completeUnitOfWork takes over: complete it, then move to its sibling if it has one (the sibling still needs its own begin, so control goes back to the main loop), otherwise climb return and complete the parent as well. That do…while does by hand what the call stack did when a recursive call returned. When return is null the root has completed, the cursor is null, and the loop ends.
Running prepareFreshStack(buildTree()); workLoopSync(); prints the same fourteen lines as the recursive version, in the same order.
Step through that run, one unit of work per step, and watch the cursor move:
Step 1 of 9
prepareFreshStackpointsworkInProgressatHostRoot, andworkLoopSyncstarts. Its own frame is the only one on the call stack, and it stays the only one.- Unit 1:
beginWork(HostRoot)printsbegin HostRootand returns itschild. The cursor moves down toApp, andperformUnitOfWorkreturns. - Unit 2:
begin App, and the cursor followschildtodiv. - Unit 3:
begin div.div.childish1, the first of three children. - Unit 4:
begin h1, and the cursor is on#text. The tree is four levels deep and the call stack has not grown. - Unit 5:
#texthas no child, socompleteUnitOfWorkcompletes it, climbsreturntoh1, completesh1and stops at itssibling,Counter. Three lines in one unit. - Unit 6:
begin Counter,complete Counter, and the cursor takessiblingtofooter. - Unit 7:
footerbegins and completes. It has no sibling, so thedo…whileclimbsreturnand completesdiv,AppandHostRoot.HostRoot.returnis null, so the cursor is null. workInProgressis null and the loop ends: the same fourteen lines as the recursion, in the same order. Between any two units, the whole position was that one variable.
Highlighted line: 3.
/** Start a walk: point the cursor at the top of a tree. */
export function prepareFreshStack(root: Fiber): void {
workInProgress = root;
}Highlighted line: 2.
Highlighted line: 2.
Highlighted line: 2.
Highlighted line: 2.
Highlighted line: 2.
Highlighted line: 2.
Highlighted line: 2.
Highlighted line: 2.
Highlighted line: 2.
export function workLoopSync(): void {
while (workInProgress !== null) performUnitOfWork(workInProgress);
}Highlighted lines: 2, 4, 9 to 10.
Highlighted lines: 2, 4, 9 to 10.
Highlighted lines: 2, 4, 9 to 10.
Highlighted lines: 2, 4, 9 to 10.
Highlighted lines: 2 to 3.
Highlighted lines: 2 to 3.
Highlighted lines: 2 to 3.
function performUnitOfWork(unitOfWork: Fiber): void {
const next = beginWork(unitOfWork);
if (next === null) completeUnitOfWork(unitOfWork);
else workInProgress = next;
}
/** On the way DOWN. Returns the next fiber to work on: the first child, or null. */
function beginWork(fiber: Fiber): Fiber | null {
console.log(`begin ${getFiberName(fiber)}`);
return fiber.child;
}Highlighted lines: 2 to 12.
Highlighted lines: 2 to 8.
Highlighted lines: 2 to 6, 10 to 12.
function completeUnitOfWork(unitOfWork: Fiber): void {
let completedWork: Fiber | null = unitOfWork;
do {
completeWork(completedWork);
const sibling: Fiber | null = completedWork.sibling;
if (sibling !== null) {
workInProgress = sibling;
return;
}
completedWork = completedWork.return;
workInProgress = completedWork;
} while (completedWork !== null);
}Stopping halfway
Between two units of work, what state does this walk have? Nothing is on the call stack: performUnitOfWork has returned. There is only the cursor. So stopping is leaving the loop, and resuming is entering it again. This continues src/work-loop.ts, at the end of the file:
/** FAKE: real React asks "is my time slice over?". We count units of work instead. */
let budget = 0;
function shouldYield(): boolean {
return budget === 0;
}
export function workLoopConcurrent(units: number): void {
budget = units;
while (workInProgress !== null && !shouldYield()) {
performUnitOfWork(workInProgress);
budget--;
}
}
/** Lets the outside see where the walk stopped. */
export function getWorkInProgress(): Fiber | null {
return workInProgress;
}It is the same loop with one more condition. A short script, src/demo.ts, walks the tree once in one go, then again with a budget of five units, waits a second, and resumes with workLoopSync. The diagram below runs it and shows its lines as they run.
Full src/demo.ts
import { buildTree } from './tree.ts';
import { getFiberName } from './fiber.ts';
import { getWorkInProgress, prepareFreshStack, workLoopConcurrent, workLoopSync } from './work-loop.ts';
const root = buildTree();
console.log('--- one go ---');
prepareFreshStack(root);
workLoopSync();
console.log('\n--- again, with a budget of 5 units ---');
prepareFreshStack(root);
workLoopConcurrent(5);
console.log(`paused at ${getFiberName(getWorkInProgress()!)}`);
// The loop has returned. The call stack is empty. Anything can run now.
setTimeout(() => {
console.log('\n--- one second later: resume ---');
workLoopSync();
}, 1000);Seven fibers, a budget of five. Before stepping through the run, guess where it stops and how many lines it prints first.
The diagram puts the second run next to the recursive walk, so you can watch where each one can stop. The output panel prints what src/demo.ts prints.
Output
--- one go ---begin HostRootbegin Appbegin divbegin h1begin #textcomplete #textcomplete h1begin Countercomplete Counterbegin footercomplete footercomplete divcomplete Appcomplete HostRoot--- again, with a budget of 5 units ---begin HostRootbegin Appbegin divbegin h1begin #textcomplete #textcomplete h1paused at Counter--- one second later: resume ---begin Countercomplete Counterbegin footercomplete footercomplete divcomplete Appcomplete HostRootStep 1 of 12
- Both walks start at
HostRoot. On the left,walk(tree)has been called: one frame on the call stack. On the right,prepareFreshStackpointsworkInProgressatHostRoot, andworkLoopConcurrent(5)sets the budget to 5. Its own frame is the only one on that stack. - One unit of work. Both walks print
begin HostRoot.beginWorkreturnsHostRoot.child, so the cursor moves down toAppand the budget drops to 4. On the left,walk(HostRoot)is about to start itsforloop. - Unit 2:
begin App. The left has a second frame,walk(App), and the frame under it is onchild 1/1. The right still has one variable:workInProgressis nowdiv, budget 3. - Unit 3:
begin div. Three frames on the left. On the right the cursor moves todiv.child, which ish1, the first of three children. Budget 2. - Unit 4:
begin h1. The recursion is four calls deep; the fiber loop’s stack has not grown. The cursor is on#text, budget 1. - Unit 5 prints three lines.
#texthas no child, socompleteUnitOfWorkcompletes it, climbsreturntoh1, completesh1and takes itssibling,Counter. On the left the same lines return two calls:walk(div)is on top again, its loop still onchild 1/3. Budget 0. shouldYield()is true, soworkLoopConcurrentreturns and the demo printspaused at Counter. The loop’s call stack is empty: its whole position isworkInProgress, and the browser has the thread. The recursion can’t stop here. Its position is three frames on the call stack, so it carries on withCounterwhile a click waits.- To give the thread back, the recursion would have to return every frame, and its place in
walk(div)’s loop would go with them. So React 15 never yielded: it runsfooterand completesdiv,AppandHostRoot, all fourteen lines in one block. Only now can the browser handle the click and paint. - A second later the
setTimeoutcallback callsworkLoopSync, a different loop. It needs nothing from the old one:workInProgressstill points atCounter. It ignores the budget. - Unit 6:
begin Counter, thencomplete Counter, because it has no child. Itssiblingisfooter. - Unit 7:
footerbegins and completes. It has no sibling, so thedo…whileclimbsreturnand completesdiv,AppandHostRoot.HostRoot.returnis null, and so isworkInProgressnow. - The cursor is null and
workLoopSyncreturns. The fiber loop printed the same fourteen lines as the recursion, seven before the pause and seven after it, with the browser free in between. The recursion printed them with no gap at all.
Highlighted line: 1.
Highlighted lines: 2 to 3.
Highlighted lines: 2 to 3.
Highlighted lines: 2 to 3.
Highlighted lines: 2 to 3.
Highlighted lines: 3 to 4.
Highlighted line: 3.
Highlighted lines: 1 to 5.
export function walk(node: TreeNode): void {
console.log(`begin ${node.name}`);
for (const child of node.children) walk(child);
console.log(`complete ${node.name}`);
}Highlighted line: 3.
/** Start a walk: point the cursor at the top of a tree. */
export function prepareFreshStack(root: Fiber): void {
workInProgress = root;
}Highlighted lines: 1 to 3.
Highlighted line: 2.
Highlighted line: 2.
Highlighted line: 2.
export function workLoopSync(): void {
while (workInProgress !== null) performUnitOfWork(workInProgress);
}Highlighted lines: 2, 4, 9 to 10.
Highlighted lines: 2, 4, 9 to 10.
Highlighted lines: 2, 4, 9 to 10.
Highlighted lines: 2, 4, 9 to 10.
Highlighted lines: 2 to 3.
Highlighted lines: 2 to 3.
Highlighted lines: 2 to 3.
function performUnitOfWork(unitOfWork: Fiber): void {
const next = beginWork(unitOfWork);
if (next === null) completeUnitOfWork(unitOfWork);
else workInProgress = next;
}
/** On the way DOWN. Returns the next fiber to work on: the first child, or null. */
function beginWork(fiber: Fiber): Fiber | null {
console.log(`begin ${getFiberName(fiber)}`);
return fiber.child;
}Highlighted lines: 2 to 12.
Highlighted lines: 2 to 8.
Highlighted lines: 2 to 6, 10 to 12.
function completeUnitOfWork(unitOfWork: Fiber): void {
let completedWork: Fiber | null = unitOfWork;
do {
completeWork(completedWork);
const sibling: Fiber | null = completedWork.sibling;
if (sibling !== null) {
workInProgress = sibling;
return;
}
completedWork = completedWork.return;
workInProgress = completedWork;
} while (completedWork !== null);
}Highlighted line: 6.
Highlighted lines: 7 to 9.
Highlighted lines: 7 to 9.
Highlighted lines: 7 to 9.
Highlighted lines: 7 to 9.
Highlighted lines: 1 to 3, 7.
function shouldYield(): boolean {
return budget === 0;
}
export function workLoopConcurrent(units: number): void {
budget = units;
while (workInProgress !== null && !shouldYield()) {
performUnitOfWork(workInProgress);
budget--;
}
}Highlighted lines: 1 to 2.
Highlighted line: 3.
Highlighted lines: 5 to 9.
prepareFreshStack(root);
workLoopConcurrent(5);
console.log(`paused at ${getFiberName(getWorkInProgress()!)}`);
// The loop has returned. The call stack is empty. Anything can run now.
setTimeout(() => {
console.log('\n--- one second later: resume ---');
workLoopSync();
}, 1000);Seven lines, not five. A unit of work is one begin plus every complete that follows from it: the fifth unit began the text, completed it, completed h1, and moved the cursor sideways to Counter. Then the budget was zero and the loop returned.
For a full second none of this code was running and the call stack was empty. In a browser, that is time for a click handler and a paint. Then I resumed with workLoopSync, the other loop, and it did not matter: the loops have no memory. Everything the walk knows is the cursor plus the pointers in the tree. This is the stop after complete h1 that the recursive version could not give me.
What I simplified
- The fibers are linked by hand. Real fibers are created from JSX elements.
beginWorkandcompleteWorkonly log. In React, begin is where components are called and complete is where DOM nodes are created.- A real fiber has many more fields. I kept eight: the three pointers this walk needs and five that say what a fiber is.
shouldYieldcounts units. The real one asks a clock, and something has to decide when to resume; here that is asetTimeout.
Where this goes
A tree stored as a linked list can be paused. That is the whole reason fibers exist, and everything React calls "concurrent" starts from it.
The next step is to make the two logging functions do real work. Once elements, this walk and a small DOM layer are put together, beginWork will turn elements into child fibers, completeWork will create DOM nodes, and the first tree will appear on screen. The loop itself will not change.