← Back to React, page 5

react-0085 · Hard senior

Explain React's Fiber architecture and scheduler. How can React pause, resume and discard renders, and what do lanes and priorities do?

Fiber is React's data structure and work loop: each element becomes a fiber node, and rendering is done as small units of work that can be paused between units. Updates get a lane (priority). Urgent lanes, such as typing and clicks, are rendered first. Non-urgent ones, such as transitions and deferred values, render in the background through the scheduler and are restarted or dropped when newer urgent work arrives. Only the commit phase must be synchronous.

Full answer

Before Fiber (React 15), rendering was a recursive stack walk that could not be interrupted. A large update blocked the main thread until it finished. Fiber, introduced in React 16, replaced the recursion with a linked data structure and a loop, so work can stop and continue.

A fiber is a plain object for one unit of work: it holds the component type, props, state, a pointer to its parent, child and sibling, and the pending work. React keeps two trees. The current tree is what is on screen. The work-in-progress tree is built during render. When rendering finishes, the commit phase swaps them by changing one pointer.

The work loop processes one fiber at a time: beginWork calls your component and decides on children, completeWork builds DOM nodes and collects effects on the way back up. In concurrent mode the loop checks shouldYield between fibers. If the time slice (about 5 ms) is used up, it hands control back to the browser through the scheduler (a message channel based task queue), so input and painting can happen, and resumes later.

Priorities are expressed as lanes, bits in a bitmask. Discrete events (click, key press) get the highest lane (SyncLane), continuous events (scroll, pointer move) get a lower one, transitions and deferred values get transition lanes, and offscreen work gets the lowest. When a higher lane is scheduled during a lower lane render, React abandons the work-in-progress tree and starts again with the urgent lane. Starved lower lanes eventually expire and are rendered anyway.

Consequences for code. Render functions must be pure, because they may run more than once or be thrown away, and StrictMode double calls them to expose impurities. Side effects belong in effects, which run only after commit. The render phase can be interrupted, the commit phase cannot.

useDeferredValue(value) shows the idea in practice: the urgent render updates the input with the new value at once, while a background render tries to update the deferred value. If the user types again before it finishes, the older background render is discarded and only the latest value is rendered. The example proves this with logging.

Fiber does not make code faster. It makes work interruptible and prioritized, so the interface stays responsive.

jsx
import { memo, useDeferredValue, useState } from 'react';

const COURSES = Array.from({ length: 300 }, (_, i) => 'React lesson ' + (i + 1));

const Results = memo(function Results({ query }) {
  console.log('rendering results for "' + query + '"');
  const matches = COURSES.filter((c) => c.toLowerCase().includes(query.toLowerCase()));
  return <p>{matches.length} matches</p>;
});

export default function Search() {
  const [query, setQuery] = useState('');
  const deferredQuery = useDeferredValue(query);

  return (
    <div>
      <input aria-label="Search" value={query} onChange={(e) => setQuery(e.target.value)} />
      <Results query={deferredQuery} />
    </div>
  );
}

The check changed the input to "r", "re" and "rea" in quick succession inside one batch of work. The input updated each time, but the background render of Results ran only for the latest value. Output of the run: rendering results for "" rendering results for "rea" input value at the end: rea

Key points

  • A fiber is a unit of work. React keeps a current tree and a work-in-progress tree, swapped at commit.
  • Concurrent rendering yields between fibers (about 5 ms slices) so the browser can handle input.
  • Lanes give updates priorities. Urgent updates interrupt and restart lower-priority renders.
  • Render must be pure because it can be paused, repeated or discarded. Commit is synchronous.
  • useDeferredValue and transitions use low-priority lanes, so intermediate values may never render.

Common mistakes

  • Saying Fiber makes React faster instead of interruptible.
  • Writing impure render functions and then being surprised by double renders.
  • Putting side effects in the render phase.
  • Believing the commit phase can be paused.
  • Expecting useDeferredValue to delay or debounce by a fixed time.

Follow-ups

  • Why does StrictMode render components twice in development?
  • What is the difference between a transition and a debounce?
  • What happens to a Suspense fallback when a transition is in progress?

Tips

  • Draw the two trees and the pointer swap. It shows you understand the model.
  • Separate render phase (pausable) and commit phase (not).
  • Give useDeferredValue as the practical example.