Detailed Explanation of React Fiber Architecture Principles and Core Mechanisms

Detailed Explanation of React Fiber Architecture Principles and Core Mechanisms

1. Problem Background: Bottlenecks of React 15 Architecture

React 15 and earlier versions used the Stack Reconciler for Virtual DOM diffing (Diff algorithm) and updates. Its core issues were:

  • Non-interruptible Recursive Updates: When the component tree had deep nesting or required heavy computation for updates, the JavaScript main thread would be occupied for a long time, preventing the browser from handling high-priority user interactions or rendering tasks, leading to stuttering.
  • Lack of Priority Scheduling: All update tasks were treated equally, unable to distinguish the urgency between user interactions (e.g., input field typing) and data rendering (e.g., list updates).

2. Design Goals of the Fiber Architecture

React 16 introduced the Fiber architecture with the following core objectives:

  1. Interruptible and Resumable: Split recursive, synchronous updates into multiple asynchronous, interruptible task units.
  2. Priority Scheduling: Assign priorities based on task types (e.g., animations, user input), allowing high-priority tasks to cut in line.
  3. Support for Concurrent Rendering: Lay the foundation for the subsequent Concurrent Mode.

3. Core Concepts of Fiber

3.1 Fiber Node

A Fiber is an internal work unit in React, essentially a JavaScript object that stores the following information:

{
  type: 'div',           // Node type (component, HTML tag)
  key: null,             // Unique identifier
  stateNode: divDOM,     // Corresponding real DOM node
  return: Fiber,         // Parent node
  child: Fiber,          // First child node
  sibling: Fiber,        // Next sibling node
  alternate: Fiber,      // Points to the backup of the current Fiber (used for Diff comparison)
  effectTag: Placement,  // Side effect tag (addition, update, deletion)
  pendingProps: {},      // Props waiting to be updated
  memoizedProps: {},     // Currently updated props
}

3.2 Double Buffering Mechanism

React maintains two Fiber trees simultaneously:

  • Current Tree: The Fiber tree corresponding to the content currently displayed on the screen.
  • WorkInProgress Tree: The new Fiber tree being constructed.
    The two trees reference each other via the alternate pointer. After an update is complete, the pointer is switched directly, avoiding frequent object creation.

4. Fiber Workflow (Reconciliation + Commit)

4.1 Phase One: Reconciliation (Interruptible)

  1. Traversal Phase:

    • Start from the root node, process each Fiber node in a depth-first traversal manner.
    • For each node, execute beginWork: call rendering logic based on component type (function component/class component), generate child nodes, and mark side effects (e.g., if DOM updates are needed).
    • If no child node exists, jump to the sibling node via the sibling pointer.
  2. Interruption and Resumption Mechanism:

    • Task units are executed during the browser's idle time per frame (simulated via requestIdleCallback).
    • If the current frame's time runs out, the update is paused, control is returned to the browser, and execution continues in the next frame.
  3. Complete Example (Simplified):

    // Before update: A -> B -> C (depth-first traversal)
    // After interruption: Record the currently processed node B, resume from B's child node C next time
    

4.2 Phase Two: Commit (Non-interruptible)

  1. Side Effect Application: Traverse the WorkInProgress tree and execute DOM updates (add, delete, modify) based on the effectTag.
  2. Lifecycle Invocation: Execute side effect hooks such as componentDidMount, useEffect.
  3. Tree Switching: Set the WorkInProgress tree as the Current Tree, completing the render.

5. Principles of Priority Scheduling

React internally defines priority levels (e.g., Immediate, UserBlocking, Normal, Low) and schedules tasks through the following steps:

  1. Task Classification: Assign priorities based on the update source (e.g., event handler, network request).
  2. High-Priority Task Cutting: If a low-priority task encounters a high-priority task during execution, interrupt the current task and regenerate the WorkInProgress tree for the high-priority task.
  3. Discarding Stale Renders: If an update has been overridden by a higher-priority update, skip its rendering phase.

6. Practical Application Scenarios

  • Input Field Responsiveness Optimization: When a user types, updates to the input field (high priority) interrupt list rendering (low priority), ensuring smooth input.
  • Suspense Asynchronous Loading: Fiber supports marking asynchronously loaded components as "suspended," resuming rendering once data is ready.

7. Summary

The Fiber architecture achieves a smoother user experience by decomposing synchronous updates into asynchronous, interruptible tasks, combined with priority scheduling and a double buffering mechanism, laying the foundation for React's concurrent features.