Core Principles of React Fiber Architecture

Core Principles of React Fiber Architecture

Problem Description
React Fiber is a new reconciliation engine introduced in React 16. It reimplements the diff algorithm of the virtual DOM, with the core goal of supporting asynchronous interruptible rendering to solve page stuttering issues during updates in large applications. Please explain how the Fiber architecture achieves interruptible updates and priority scheduling.

Knowledge Explanation

  1. Background: Limitations of the Stack Reconciler

    • Before React 16, React used an algorithm known as the "Stack Reconciler."
    • Its working mode was recursive. When starting a component update (e.g., setState), the Reconciler would begin from the root component, recursively call each component's render method to generate a new virtual DOM tree, and then perform a complete Diff comparison with the old tree. This "Render Phase" and "Diff" process was synchronous and executed in one go.
    • Drawback: If the component tree is very large, this recursive calculation process would occupy the JavaScript main thread for a long time. Since the browser's main thread also handles tasks like layout and painting, prolonged occupation by JS calculations would prevent timely responses to user interactions (like clicks, inputs) and cause animation frame drops, leading to a perceived page stutter.
  2. Fiber's Solution: Interruptibility and Splitting

    • The fundamental idea of Fiber is to break down a long synchronous update task into multiple small, asynchronous work units and assign them different priorities.
    • Achieving this goal requires two core capabilities:
      • Interruptibility: Allows React to pause the current update after completing a small unit, yielding the main thread to higher-priority tasks (like user input), and resume later.
      • Resumability: When React pauses, it needs to save the current progress so it can continue from where it left off.
  3. Fiber Node: The Data Structure of a Work Unit

    • To achieve interruptibility and resumability, React no longer simply recurses through the virtual DOM tree. It transforms each virtual DOM node into a corresponding Fiber node.
    • A Fiber node is a JavaScript object containing much richer information than a regular VNode, primarily categorized into three types:
      • Instance Information: Such as type (component type, e.g., div or MyComponent), stateNode (the corresponding real DOM node or class component instance), props.
      • Structural Information: Describes the tree relationships formed by Fiber nodes.
        • return: Points to the parent Fiber node.
        • child: Points to the first child Fiber node.
        • sibling: Points to the next sibling Fiber node.
        • (This forms a linked list tree, changing traversal from recursion to loops, which is key to enabling interruptibility.)
      • Side Effects and Work Information:
        • flags (called effectTag in older React versions): Marks what kind of side effect this Fiber node needs to execute in this render (e.g., Placement-insert, Update-update, Deletion-delete).
        • alternate: Points to another Fiber node, usually the "old" or "new" Fiber corresponding to the current node, used for Diff comparison.
        • lanes: A field related to priority, indicating the urgency of this update task.
  4. Work Loop and Double Buffering Mechanism

    • React maintains two Fiber trees in memory simultaneously:
      • Current Tree: The Fiber tree corresponding to the content currently displayed on screen.
      • WorkInProgress Tree: The Fiber tree being constructed in memory for the next update to render.
    • Render Phase (Render/Reconciliation Phase):
      1. After receiving an update, React assigns it a priority (Lane).
      2. Starting from the root node, React attempts to traverse the Current Tree, creating a "stand-in" (or reusing) for each Fiber node that needs an update in the WorkInProgress Tree.
      3. This traversal is not recursive but occurs within a large loop (workLoop). The loop processes only one Fiber node (one work unit) at a time.
      4. After processing a node, React checks the remaining time in the current frame (using a polyfill of requestIdleCallback). If time is sufficient, it continues to the next node; if time is nearly up, React interrupts the traversal, yielding control back to the browser to handle higher-priority tasks (like rendering, responding to user input).
      5. When the browser is idle (known via requestIdleCallback), React resumes work, continuing the traversal from the last interrupted Fiber node.
      6. During this phase, React performs the Diff algorithm, calculates what needs to be updated, and marks side effects (flags).
    • Commit Phase:
      1. Once the entire WorkInProgress Tree is fully constructed and all side effect calculations are complete, React executes this phase synchronously and in one go.
      2. In this phase, React traverses the entire WorkInProgress Tree and synchronously updates the real DOM according to the side effects marked during the Render Phase. This phase cannot be interrupted, because DOM mutations must be contiguous; otherwise, UI inconsistency would occur.
      3. After the update is complete, the WorkInProgress Tree becomes the new Current Tree for the next update.

Summary
The core principle of the Fiber architecture is to represent the component tree as Fiber nodes in a linked list structure, breaking down the rendering process into quantifiable work units. It leverages the browser's idle time for incremental rendering, checking after each small task segment if higher-priority tasks need handling, thereby achieving interruptibility and resumability. Finally, it updates the DOM in one go during the commit phase to ensure UI consistency. This greatly improves the user experience of large React applications and lays the foundation for Concurrent Mode.