Fiber

Rendering you can pause: the work loop and the two phases.

Builds on The virtual DOM and diffing.

The reconciler from chapters 5 and 6 is correct and reasonably efficient. It has one property that gets worse as apps grow: once render starts, it doesn't stop until the whole tree is done. Every component call, every diff, every DOM write happens in one uninterrupted JavaScript task. While it runs, the browser can't respond to a keystroke, run an animation frame, or paint.

React had the same property until 2017. React 16 replaced its reconciler with a new one called Fiber, built around a simple change: turn the recursion into a loop over a linked tree, so the work can stop after any node and pick up later. This chapter rebuilds the toy that way. It's the deepest chapter in Part 2, and the one that explains the most about modern React: why rendering has two phases, why render must be pure, and what makes concurrent features possible.

The problem: rendering blocks the main thread#

The browser runs your JavaScript, handles input and paints the page on one main thread. A frame at 60 Hz has about 16 ms for all of it. If one task takes 200 ms, that's a dozen frames where nothing responds.

Here's a list of 200 rows that re-renders on every keystroke, with each row artificially slow (slowDown(1) busy-waits for 1 ms, standing in for real work). The frame counter at the top is driven by requestAnimationFrame, so it only advances when the browser gets to paint. Type quickly in the box with the checkbox off, using the stage 6 toy.

Blocking versus time-sliced rendering
<p>Frames painted: <strong id="frames">0</strong></p>
<label><input type="checkbox" id="sliced"> Render with the Fiber toy (stage 7)</label>
<p><input id="q" placeholder="Type fast here" autocomplete="off"></p>
<div id="blocking"></div>
<div id="sliced-root" style="display: none"></div>
Nothing logged yet.

With the recursive toy, each keystroke blocks for over 200 ms. Letters appear in bursts, and the frame counter stalls while you type. Now check the box and type again. The letters appear as you type, the counter keeps moving, and the list catches up a moment later. The total work is the same (actually a little more). What changed is that it's chopped into 5 ms slices with the browser getting the thread back in between.

Why can't the recursive version just pause? Because its progress lives on the call stack. Halfway through, "where we are" is a dozen nested reconcile calls, each with local variables and a loop index. JavaScript has no way to suspend that stack and resume it in a later task. To pause, the progress has to live somewhere else: in data you can hold in a variable.

Build it: fibers and a work loop#

A fiber is a stack frame you can keep#

A fiber is a plain object for one element in the tree. It holds what the recursive version kept in locals, plus three pointers that make the tree walkable without recursion:

{
  type, props, key,
  dom: null,         // the DOM node, for host fibers like "div" and text
  child: null,       // first child
  sibling: null,     // next sibling
  return: null,      // parent: where to go when this subtree is done
  index: 0,          // position among siblings
  alternate: null,   // the same fiber in the other tree (below)
  flags: 0,          // what the commit phase must do: Placement, Update
}

With child, sibling and return, you can visit every node in depth-first order using one variable, the next fiber to work on. The rule, in performUnitOfWork:

  1. Do the work for this fiber (beginWork): call the component or look at the element, and create fibers for its children.
  2. If it has a child, that's the next unit.
  3. Otherwise this fiber is complete (completeWork). If it has a sibling, that's next. If not, climb return to the parent, which is now complete too, and check its sibling. Repeat until you find a sibling or get back to the root.
function performUnitOfWork(fiber) {
  debug.onUnit?.(fiber);
  beginWork(fiber); // call the component, diff its children

  // Next unit: the first child. With no child, this fiber is complete; so is
  // every ancestor we climb through (via return) until one has a sibling.
  if (fiber.child) return fiber.child;
  let next = fiber;
  while (next) {
    completeWork(next);
    if (next.sibling) return next.sibling;
    next = next.return;
  }
  return null; // back at the root: the render phase is done
}

That's the same depth-first walk the recursion did. The difference is that between any two units the entire state of the walk is nextUnitOfWork, one variable. You can stop, run other code, and continue.

beginWork does what reconcile did on the way down: for a component it calls the function, for a host element it takes props.children, and either way it hands the new child elements to reconcileChildren. completeWork runs on the way up, once all of a fiber's children are done, and creates the fiber's DOM node if it's new, appending its children's nodes into it. New subtrees are built off screen, as in chapter 4.

The loop yields#

The work loop does units until it runs out of time:

function workLoop() {
  deadline = performance.now() + debug.timeSlice; // 5 ms
  if (!nextUnitOfWork) prepareNextRoot();
  while (nextUnitOfWork && !shouldYield()) {
    nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
  }
  if (!nextUnitOfWork && wipRoot) commitRoot();
  if (nextUnitOfWork || rootQueue.size) scheduleWork(); // yield, continue later
}

scheduleWork posts a message to a MessageChannel, which runs workLoop again as a new task. Between tasks the browser handles input and paints. That's the whole trick behind "time slicing".

Why not requestIdleCallback, the browser API made for "run this when you're idle"? Early Fiber prototypes and many tutorials use it, but it can wait a long time before firing, it wasn't available in every browser when React built its scheduler, and React wanted control over priorities. React ships its own Scheduler package instead, which does what the toy does: a MessageChannel loop with a 5 ms budget per slice.

The work loop, one fiber at a time
render phase · nextUnitOfWork = AppAppbegundivcreatedh1ulli Ali Bchildsiblingreturn (back to the parent)DOM: untouched until commit
Step 1 of 8

Past the root fiber, the first unit of work is App. beginWork on App calls the component, and reconcileChildren turns its output into a div fiber, linked as App's child.

Two phases: render, then commit#

The recursive toy patched the DOM while it walked. The fiber toy can't, and the reason is the whole point of this chapter. If the loop pauses halfway with some DOM nodes already patched, the browser paints a screen that's half old, half new. The user sees an inconsistent UI.

So the work is split into two phases:

  • Render phase: walk the tree, call components, diff children, and record what needs to change as flags on fibers (Placement for new or moved nodes, Update for changed props, plus a list of deletions). No DOM writes. This phase can pause, resume, and in real React even be thrown away and restarted.
  • Commit phase: once the whole tree is done, walk it once and apply every flag to the DOM, synchronously, without yielding. The user goes from the old screen to the complete new one in a single step.
function commitRoot() {
  const root = wipRoot;
  deletions.forEach(commitDeletion);
  for (let fiber = root.child; fiber; fiber = nextFiber(fiber, root)) commitWork(fiber);
  root.dom.__rootFiber = root; // the finished tree becomes the current tree
  wipRoot = null;
  debug.onCommit?.(root);
}

function commitWork(fiber) {
  if (fiber.dom && fiber.flags & Update) {
    updateDom(fiber.dom, fiber.alternate.props, fiber.props);
  }
  if (fiber.flags & Placement) commitPlacement(fiber);
}

commitPlacement inserts a fiber's DOM nodes before the right sibling. Finding that sibling is fiddly because components have no DOM node of their own, so the toy (like React's getHostSibling) walks forward through siblings, and up through component parents, to find the next DOM node that's already in place.

You can watch the two phases separately. This sandbox puts the toy in manual mode: nothing happens until you press Step, which performs exactly one unit of work. The screen keeps showing the old version during the entire render phase, and changes all at once on the step that commits.

Step through the work loop
<button id="step">Step (one unit of work)</button>
<button id="update">Queue an update</button>
<div id="root" style="margin-top: 8px"></div>
Nothing logged yet.

Notice the order of the log: root, then App, then div, h3 and its text children, then ul, the first li, and so on, exactly the child, sibling, return walk from the diagram. And notice that "screen shows" never changes until the line after COMMIT.

Current and work-in-progress trees#

The render phase needs the previous tree to diff against, and it must not disturb it, since that tree describes what's still on screen. So there are two trees:

  • The current tree: what was last committed. The container's __rootFiber in the toy, root.current in React.
  • The work-in-progress tree: being built by the render phase.

Each fiber in one tree points to its counterpart in the other through alternate. When reconcileChildren finds a matching old child (same key and type, as in chapter 6), it doesn't allocate a new fiber. It calls createWorkInProgress, which reuses the old fiber's alternate from two renders ago and resets it:

function createWorkInProgress(current, props) {
  let wip = current.alternate;
  if (!wip) {
    wip = createFiber(current.type, props, current.key);
    wip.alternate = current;
    current.alternate = wip;
  }
  wip.props = props;
  wip.dom = current.dom;
  wip.index = current.index;
  wip.flags = 0;
  wip.child = null;
  wip.sibling = null;
  return wip;
}

On commit, the work-in-progress tree becomes current. Every component has at most two fibers, flipping roles on each render. Graphics programmers call this double buffering: draw the next frame off screen, then swap.

Current and work-in-progress trees
root.currentcurrentAppdivli
Step 1 of 3

The current tree describes what's on screen. The root's current pointer points at it. Each fiber holds the props, state and DOM node of one element.

Keeping the old tree intact is also what makes it safe to abandon a render. If something more urgent comes in, React can drop the work-in-progress tree and start over from current, and nothing on screen or in committed state was touched. The toy never abandons a render (it finishes the one in progress, then starts the next), but it has everything it would need.

What the fiber toy can do now#

Stage 7 is a complete rewrite of the reconciler, with the same rules: types (chapter 5), keys and lastPlacedIndex (chapter 6), and the same createElement, updateDom and patches log. Because fibers handle any number of children per component, fragments and components returning null or arrays work again. And render is now asynchronous: it queues work and returns. For tests, the toy exports act(callback), which runs everything synchronously, named after React's testing helper that does the same job.

Build itWalk a tree without recursion

walk(root, visit) must call visit("begin", fiber) when it first reaches a fiber and visit("complete", fiber) when that fiber's whole subtree is done, in depth-first order, using only child, sibling and return. The starter is recursive. It produces the right order, but deep trees overflow the call stack. Rewrite it as a loop. Press Check when you think it works.

// Recursive: correct order, but every level of the tree is a stack frame.
export function walk(fiber, visit) {
  visit("begin", fiber);
  for (let child = fiber.child; child; child = child.sibling) walk(child, visit);
  visit("complete", fiber);
}
Nothing logged yet.

The real thing: React's Fiber#

React's fibers are the toy's fibers with more fields. The ones you'll hear about:

ToyReact fiber fieldWhat it holds
type, keytype, elementType, key, tagThe component or host type. tag says which kind of fiber it is (function component, host component, host text, Suspense, and so on).
domstateNodeThe DOM node for host fibers (a class instance for class components).
child, sibling, return, indexsame namesThe linked tree.
propspendingProps, memoizedPropsThe props for this render, and the props it rendered with last time.
hooks (chapter 8)memoizedStateFor function components, a linked list of hooks.
flagsflags, subtreeFlags, deletionsSide effects for the commit phase. subtreeFlags lets the commit skip subtrees with nothing to do.
(none)lanes, childLanesWhich priorities of pending work this fiber and its subtree have.
alternatealternateThe counterpart in the other tree.

Its work loop is the toy's, almost line for line. In React 19.3 the yielding loop is called workLoopConcurrentByScheduler, and it reads while (workInProgress !== null && !shouldYield()) performUnitOfWork(workInProgress);, and performUnitOfWork calls beginWork, then completeUnitOfWork (which calls completeWork) when there's no child. There's also a workLoopSync without the shouldYield() check.

Not every render is sliced#

This surprises people: in React 18 and 19, most updates don't yield. React picks the loop by priority. Urgent updates, like a click or a keystroke, and default ones, like root.render or a setState after a fetch, render with workLoopSync, start to finish. Time slicing is used for non-blocking work: updates inside startTransition (and useDeferredValue), Suspense retries and offscreen prerendering. Those render with the yielding loop, and React can interrupt them, throw away the work-in-progress tree, and restart when something urgent comes in.

You can see the difference with real React. The sandbox below renders the same slow list on every keystroke. Unchecked, it's a normal update and blocks like the recursive toy. Checked, it's wrapped in startTransition, so React renders it with the yielding loop and the page stays responsive while the list catches up.

Real React: a normal update versus a transition
<p>Frames painted: <strong id="frames">0</strong></p>
<label><input type="checkbox" id="transition"> Wrap the update in startTransition</label>
<p><input id="q" placeholder="Type fast here" autocomplete="off"></p>
<div id="root"></div>

Transitions and scheduling get two full chapters, rendering and scheduling and transitions. For now, the takeaway is that Fiber is what makes them possible: without a pausable, restartable render phase, there's nothing to prioritize.

The commit phase in React#

React's commit is synchronous, like the toy's, and runs in sub-phases over the finished tree:

  1. Before mutation: read anything from the DOM that must be captured before it changes (getSnapshotBeforeUpdate in class components).
  2. Mutation: insert, update and delete DOM nodes, detach old refs. The toy's commitWork and commitDeletion live here.
  3. Switch trees: root.current = finishedWork.
  4. Layout: attach refs and run useLayoutEffect callbacks and componentDidMount/componentDidUpdate, before the browser paints.
  5. Passive effects: useEffect callbacks run later, usually after the browser has painted. Chapter 9 builds this.

Because the render phase can run more than once for one commit, or not commit at all, React requires components to be pure during render: no mutations of outside data, no subscriptions, no DOM access. Side effects belong in event handlers or effects, which only run for committed renders. Strict Mode in development renders components twice on purpose to flush out impure ones.

Pitfalls#

Check your understanding#

PredictWhich completes first?

For this tree, list the order in which fibers complete:

<App>
  <Header />
  <Main>
    <Sidebar />
    <Content />
  </Main>
</App>

Assume Header, Sidebar and Content render no children.

Quick checkWhich phase?

Which statement about React's render and commit phases is true?

Explain it out loudWhat is Fiber?

An interviewer asks: "What is React Fiber, and why did React introduce it?"

Interview angle

Say it in 30 seconds

Fiber is React's reconciler since React 16. The old one was recursive, so a render had to finish once it started, blocking input and painting. A fiber is one unit of work, an object per element linked by child, sibling and return pointers, so the work loop can process one fiber, check whether to yield, and resume later. Rendering splits into a render phase that calls components and marks changes on a work-in-progress tree, which can pause or be discarded, and a synchronous commit phase that applies them to the DOM. Current and work-in-progress trees are linked by alternate. That's what makes transitions and Suspense possible, and why render must be pure.

What is React Fiber and what problem does it solve?

intermediate

What's the difference between the render phase and the commit phase?

basic

Why must components be pure during rendering?

intermediate

What are the current and work-in-progress trees?

senior

Does React time-slice every render in React 18 and 19?

senior

How does React decide when to yield to the browser?

senior

Recap#

  • A recursive renderer keeps its progress on the call stack, so it can't stop until the whole tree is done. Long renders freeze input and painting.
  • A fiber is one unit of work: an object per element with child, sibling and return pointers. The work loop walks them depth first with one variable, so it can yield after any fiber.
  • Rendering is split in two: the render phase (call components, diff, set flags; can pause, restart or be discarded) and the commit phase (apply all DOM changes in one synchronous pass).
  • Two trees, current and work in progress, linked by alternate, give double buffering and make abandoning a render safe.
  • In React 18 and 19, only non-blocking work (transitions, deferred values, Suspense retries) is time-sliced; urgent and default updates use the synchronous loop. Render must be pure because it can run without committing.

Sources#