Sub topic 12
Fiber: the data structure behind the reconciler
This chapter assumes you know the render phase and commit phase, the idea that React compares an old tree with a new one, and how useState triggers a re-render. You don't need to read React's source. The goal is a working mental model of what React keeps in memory between renders. That model explains why rendering can pause, why hook order matters, and why render functions must be pure.
Why React needed a new data structure
Before React 16, the reconciler walked the element tree with ordinary recursive function calls. Recursion uses the JavaScript call stack, and you can't pause a call stack halfway and resume it later. A large update therefore held the main thread until it finished. Typing, scrolling, and animations stalled in the meantime.
Fiber is the rewrite of the reconciler that replaced the call stack with a data structure React controls. Each unit of work is an object. The pointers between those objects record where React is in the tree. Because that position is plain data, React can stop after any unit, let the browser handle input, and continue later. It can also drop the work entirely.
What a fiber is
A fiber is a plain JavaScript object. React creates one for each component instance, each host element such as div, text nodes, and a few internal node types. You can think of it as a unit of work with a job description attached.
Don't confuse fibers with elements. They are different objects with different lifetimes:
| Row | Element | Fiber |
|---|---|---|
| Created by | JSX / `createElement`, on every render | React, when a node first appears |
| Mutability | Immutable description | Mutable, updated by React |
| Lifetime | One render | As long as the node stays in the tree |
| Holds state | No | Yes (hook state, DOM node reference) |
The fields that matter for this chapter are below. The names are React's internal ones.
| Field | Meaning |
|---|---|
| `type` | The component function, class, or host tag string |
| `key` | The key from the element, used when matching children |
| `stateNode` | The real DOM node for host fibers, or the instance for class components |
| `return` | Pointer to the parent fiber |
| `child` | Pointer to the first child fiber |
| `sibling` | Pointer to the next sibling fiber |
| `pendingProps` / `memoizedProps` | Props for the render in progress, and props from the last completed render |
| `memoizedState` | The state from the last render. For function components this holds the linked list of hooks |
| `flags` | What the commit phase must do: place, update, delete, and so on |
| `lanes` | Which priority levels of pending updates this fiber has |
| `alternate` | Pointer to the other copy of this fiber (see double buffering below) |
The tree is a linked list with three pointers
A fiber doesn't hold an array of children. It points to its first child. Each child points to its next sibling, and every fiber points back to its parent with return. That is enough to visit the whole tree without recursion.
React walks this structure in a fixed order. It goes down with child, and it handles each fiber in two steps:
- Begin work. React renders the component (calls your function) and reconciles its children against the new elements. It then returns the first child as the next unit of work.
- Complete work. When a fiber has no child, React completes it. For host fibers this means creating the DOM node (not yet attached) and gathering flags. Then React moves to the
siblingif there is one, or back up throughreturn.
Because the "current position" is just one variable pointing at a fiber, the loop can stop between any two units.
A runnable model of the work loop
The script below is a toy version, not React's code. It builds fibers from a small element tree and walks them with child, sibling, and return. It also yields after a fixed number of units, which is what React's concurrent work loop does when its time slice runs out. Run it with Node.
// Elements: plain descriptions, like the output of JSX.
const h = (type, ...children) => ({ type, props: { children } });
const tree = h('App',
h('Header', h('Title')),
h('List', h('Item'), h('Item'))
);
function createFiber(element, parent) {
return { type: element.type, props: element.props, return: parent, child: null, sibling: null };
}
// Turn child elements into linked child fibers.
function reconcileChildren(fiber) {
let prev = null;
fiber.props.children.forEach((el, i) => {
const child = createFiber(el, fiber);
if (i === 0) fiber.child = child;
else prev.sibling = child;
prev = child;
});
}
// Do one unit of work and return the next fiber to work on.
function performUnitOfWork(fiber) {
console.log('begin ', fiber.type);
reconcileChildren(fiber);
if (fiber.child) return fiber.child;
let node = fiber;
while (node) {
console.log('complete', node.type);
if (node.sibling) return node.sibling;
node = node.return;
}
return null;
}
let nextUnitOfWork = createFiber(tree, null);
function workLoop(budget) {
let units = 0;
while (nextUnitOfWork && units < budget) {
nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
units++;
}
if (nextUnitOfWork) {
console.log('--- yield to the browser ---');
setTimeout(() => workLoop(budget), 0); // resume later
} else {
console.log('--- render finished, ready to commit ---');
}
}
workLoop(4);The output shows begin App, begin Header, begin Title, complete Title, then a yield. The loop resumes from the stored nextUnitOfWork and finishes the rest. The real loop checks shouldYield(), which compares elapsed time with a slice of about 5 ms, instead of counting units. Updates that React treats as urgent, such as discrete input events, use a synchronous loop that never yields.
Double buffering: current and work-in-progress
React keeps two versions of the fiber tree.
- The current tree is what is on screen now.
- The work-in-progress tree is the one React builds during a render.
Each fiber's alternate field points to its counterpart in the other tree. When a render starts, React reuses the alternate fibers where it can, so it mostly recycles two objects per node. It doesn't allocate a new tree on every update.
When the render phase finishes, the commit phase applies the DOM changes recorded in the flags. React then points the root's current at the finished tree. That swap happens after the DOM mutations and before layout effects run, so useLayoutEffect and componentDidMount see the new tree as current. The old current tree becomes the spare for the next render.
This is what makes interruption safe. Until the swap, nothing React did during render is visible, and the current tree is untouched. React can throw the work away and restart it, for example because a more urgent update arrived. This is why the chapter on Strict Mode insisted that render functions be pure. React may call a component several times for one visible update, and each call must give the same result and change nothing outside itself.
Lanes: priority stored on the fiber
Each update is assigned a lane, which is a bit in a bitmask, based on where it came from. A click handler gets a high-priority lane. An update wrapped in startTransition gets a lower one. Fibers record lanes for their own pending work and childLanes for work somewhere below them.
During a render, React picks the lanes it will work on. It skips fibers whose lanes don't overlap, and it can skip entire subtrees whose childLanes are empty. A low-priority render can be interrupted when a higher-priority update arrives. The urgent update renders and commits first, and the transition then restarts on top of the new state.
Fibers and hooks
For a function component, memoizedState on the fiber points to the first hook, and each hook object points to the next. React doesn't store hooks by name. It reads them by position in that list, in call order. This is why calling a hook inside an if or a loop breaks your component: on the next render the list no longer lines up with your calls. The fiber is also why state survives between renders even though your function's local variables don't. The state lives on the fiber, not in the function call.
Bailouts use the fiber too. If a fiber's pendingProps are identical (same object) to memoizedProps, and it has no pending lanes and no changed context, React skips calling the component. It then checks childLanes to see whether any descendant still needs work. This is the mechanism behind memo and the reason a new object or function prop defeats it.
Common errors
- Treating fibers as public API. React DOM puts internal properties on DOM nodes (names starting with
__reactFiber$), and tools can read them. Their shape changes between versions. Application code that depends on them breaks on upgrade. - Believing the virtual DOM is the fiber tree. Elements are the cheap, per-render description. Fibers are React's long-lived bookkeeping, and they also hold state, priorities, and effect flags.
- Assuming one render call means one visible update. With concurrent rendering and Strict Mode, a component function can run more than once before a commit, or run and be discarded. Side effects in render bodies, such as mutating a module variable or writing to the DOM, show up as duplicated or lost work.
- Expecting interruptible rendering from the legacy root. Time slicing and transitions need
createRoot(React 18 and later). The olderReactDOM.renderruns the synchronous path. - Thinking Fiber makes renders faster. It doesn't reduce the total work. It lets React reorder, pause, and drop work so the interface stays responsive.
Exercise
In the toy work loop above, the tree is App > [Header > Title, List > [Item, Item]]. After complete Title runs, which fiber does performUnitOfWork return as the next unit of work, and which pointers did it follow to find it?
Show answer
It returns the List fiber. Title has no child and no sibling, so the loop moves to Title.return, which is Header, and completes Header. Header has a sibling pointer to List, so List becomes the next unit of work.
Exercise
A render is interrupted by an urgent click before it finishes. What happens to the work-in-progress tree, why is the screen never left half-updated, and what requirement does this place on component functions?
Show answer
React discards the work-in-progress tree and renders the urgent update first. The screen shows the current tree until the commit swaps root.current, so no partial result is ever visible. Because React may call a component several times and throw some of those results away, render functions must be pure. They must not mutate external values or the DOM during render.