How does React Fiber works? Explain in detail.
React Fiber is the complete rewrite of React's core reconciliation algorithm (introduced in React 16). Its primary purpose is to enable incremental rendering—the ability to split rendering work into chunks and spread it out over multiple frames.
1. Core Motivation: Replacing the Stack Reconciler
The legacy Stack Reconciler was synchronous and recursive. Once a tree update started, it could not be paused or aborted until the entire component tree finished rendering. In complex UIs, this caused dropped animation frames (jank) and frozen inputs.
2. The Fiber Node: Unit of Work
A Fiber is a plain JavaScript object representing a unit of work. Each React element has a corresponding Fiber node containing:
tag&type: Component type (Function, Class, HostComponent likediv)child: Pointer to the first direct childsibling: Pointer to the next siblingreturn: Pointer back to the parent FibermemoizedState: Linked list of Hooks statependingProps&memoizedProps: Input vs current propslanes: Bitmask representing priority levels (Sync, InputContinuous, Default, Idle)
3. Two-Phase Work Loop
- Render Phase (Reconciliation - Asynchronous & Interruptible):
- React processes the Fiber tree via
workLoopConcurrent. - Before processing each Fiber node, React checks
shouldYield(). If higher-priority work (like user typing or animations) arrives, React yields control to the browser. - Computes diffs and constructs an "Effect List" or work-in-progress tree without touching the DOM.
- React processes the Fiber tree via
- Commit Phase (Synchronous & Non-Interruptible):
- React applies the calculated mutations to the actual DOM in a single rapid pass.
- Executes lifecycle methods (
componentDidMount,componentDidUpdate) anduseLayoutEffecthooks synchronously. - Swaps the current tree with the work-in-progress tree (Double Buffering).
Fiber Double Buffering Diagram
flowchart TD
subgraph WorkLoop ["Concurrent Work Loop"]
C[Current Fiber Tree] -.->|Cloned to| W[Work-In-Progress Tree]
W -->|Interruptible Diffing| Diff[Compute Effect List]
end
Diff -->|Commit Phase| DOM[(Real DOM Update)]
DOM -->|Swap Pointers| C