Skip to content
Inside a Developer's Head by Jesús Quintana, home

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:

The recursive walk and its call stack
HostRootAppdivh1#textCounterfootercall stackwalk(HostRoot)child 1/1walk(App)child 1/1walk(div)child 1/3walk(h1)child 1/1(empty)

  1. walk(tree) is walk(HostRoot): one frame on the call stack. It prints begin HostRoot, and its for loop is about to call the first child.
  2. The loop calls walk(App). A second frame goes on the stack, and it prints begin App. The frame under it remembers that it is on child 1/1.
  3. walk(div): a third frame, and begin div. div has three children; its loop starts with the first, h1.
  4. walk(h1) prints begin h1. Four calls deep, and every frame under the top one is waiting inside its for loop.
  5. walk(#text) prints begin #text, has no children, prints complete #text and returns. Its frame is gone, and walk(h1) is on top again.
  6. The loop in walk(h1) has no more children, so it prints complete h1 and returns. walk(div) is on top, still on child 1/3: the only record that Counter comes next.
  7. The loop in walk(div) moves on to child 2/3 and calls walk(Counter): begin Counter, no children, complete Counter.
  8. Then child 3/3: walk(footer) begins and completes the same way.
  9. The loop in walk(div) is done: complete div, and the call returns to walk(App).
  10. complete App. One frame left.
  11. complete HostRoot, and walk(HostRoot) returns. The stack is empty and all fourteen lines are printed. Every node completed only after all of its 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);

"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:

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:

One cursor and a while loop
HostRootAppdivh1#textCounterfooterworkInProgress = Countercall stackworkLoopSync()(empty)

  1. prepareFreshStack points workInProgress at HostRoot, and workLoopSync starts. Its own frame is the only one on the call stack, and it stays the only one.
  2. Unit 1: beginWork(HostRoot) prints begin HostRoot and returns its child. The cursor moves down to App, and performUnitOfWork returns.
  3. Unit 2: begin App, and the cursor follows child to div.
  4. Unit 3: begin div. div.child is h1, the first of three children.
  5. Unit 4: begin h1, and the cursor is on #text. The tree is four levels deep and the call stack has not grown.
  6. Unit 5: #text has no child, so completeUnitOfWork completes it, climbs return to h1, completes h1 and stops at its sibling, Counter. Three lines in one unit.
  7. Unit 6: begin Counter, complete Counter, and the cursor takes sibling to footer.
  8. Unit 7: footer begins and completes. It has no sibling, so the do…while climbs return and completes div, App and HostRoot. HostRoot.return is null, so the cursor is null.
  9. workInProgress is 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.
/** 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;
}
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.

Recursion against the fiber loop
Recursion (React 15)HostRootAppdivh1#textCounterfootercall stackwalk(HostRoot)child 1/1walk(App)child 1/1walk(div)child 2/3(empty)main thread blockedno input, no paintFiber loopHostRootAppdivh1#textCounterfooterworkInProgress = Counterbudget = 0call stack(empty)

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 HostRoot

  1. Both walks start at HostRoot. On the left, walk(tree) has been called: one frame on the call stack. On the right, prepareFreshStack points workInProgress at HostRoot, and workLoopConcurrent(5) sets the budget to 5. Its own frame is the only one on that stack.
  2. One unit of work. Both walks print begin HostRoot. beginWork returns HostRoot.child, so the cursor moves down to App and the budget drops to 4. On the left, walk(HostRoot) is about to start its for loop.
  3. Unit 2: begin App. The left has a second frame, walk(App), and the frame under it is on child 1/1. The right still has one variable: workInProgress is now div, budget 3.
  4. Unit 3: begin div. Three frames on the left. On the right the cursor moves to div.child, which is h1, the first of three children. Budget 2.
  5. 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.
  6. Unit 5 prints three lines. #text has no child, so completeUnitOfWork completes it, climbs return to h1, completes h1 and takes its sibling, Counter. On the left the same lines return two calls: walk(div) is on top again, its loop still on child 1/3. Budget 0.
  7. shouldYield() is true, so workLoopConcurrent returns and the demo prints paused at Counter. The loop’s call stack is empty: its whole position is workInProgress, 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 with Counter while a click waits.
  8. 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 runs footer and completes div, App and HostRoot, all fourteen lines in one block. Only now can the browser handle the click and paint.
  9. A second later the setTimeout callback calls workLoopSync, a different loop. It needs nothing from the old one: workInProgress still points at Counter. It ignores the budget.
  10. Unit 6: begin Counter, then complete Counter, because it has no child. Its sibling is footer.
  11. Unit 7: footer begins and completes. It has no sibling, so the do…while climbs return and completes div, App and HostRoot. HostRoot.return is null, and so is workInProgress now.
  12. The cursor is null and workLoopSync returns. 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.
export function walk(node: TreeNode): void {
  console.log(`begin    ${node.name}`);
  for (const child of node.children) walk(child);
  console.log(`complete ${node.name}`);
}
/** 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;
}
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);
}
function shouldYield(): boolean {
  return budget === 0;
}

export function workLoopConcurrent(units: number): void {
  budget = units;
  while (workInProgress !== null && !shouldYield()) {
    performUnitOfWork(workInProgress);
    budget--;
  }
}
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.
  • beginWork and completeWork only 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.
  • shouldYield counts units. The real one asks a clock, and something has to decide when to resume; here that is a setTimeout.

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.