Lesson 19-Deep Dive into React’s Fiber Implementation

Since its introduction in React 16, the Fiber architecture has fundamentally transformed React’s rendering mechanism, enabling asynchronous rendering, time slicing, and Concurrent Mode. This tutorial explores Fiber’s core principles, data structures, workflows, and source code implementation to help you master React’s core technology. By the end, you’ll understand how Fiber overcomes the limitations of traditional recursive rendering and supports advanced React features.

Introduction to Fiber Architecture

What is Fiber?

Fiber is React’s core data structure and work unit, representing a node in the component tree. It replaces React 15’s recursive rendering model (known as the “Stack Reconciler”) with a linked-list structure and interruptible work loop, enabling a more flexible rendering process.

Fiber’s Goals

  1. Asynchronous Rendering: Supports task interruption and resumption to avoid blocking the main thread.
  2. Priority Scheduling: Differentiates high- and low-priority tasks to enhance user experience.
  3. Incremental Updates: Processes large component trees in chunks.

Example: From Recursion to Fiber

Traditional recursive rendering:

function render(element, container) {
  const dom = document.createElement(element.type);
  Object.keys(element.props).forEach(key => {
    dom[key] = element.props[key];
  });
  container.appendChild(dom);
  element.children.forEach(child => render(child, dom));
}
  • Recursive execution, uninterruptible, may cause jank.

Fiber rendering:

function workLoop() {
  while (nextUnitOfWork && !shouldYield()) {
    nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
  }
}
  • Interruptible, executed in chunks.

Historical Context of Fiber

React 15’s Stack Reconciler used recursive component tree traversal, which couldn’t be paused once started. As applications grew, this approach caused performance bottlenecks in complex scenarios. Fiber architecture addresses this by breaking rendering into discrete work units.

Core Principles of Fiber

Fiber Node Data Structure

Each Fiber node represents a component instance or DOM element, containing key fields (based on react-reconciler/src/ReactFiber.js):

const fiber = {
  tag: FunctionComponent,      // Node type (e.g., FunctionComponent, HostComponent)
  type: MyComponent,           // Component constructor or DOM tag
  key: null,                   // Unique identifier for Diff
  stateNode: null,             // Corresponding instance or DOM node
  props: {},                   // Current props
  pendingProps: {},           // New incoming props
  memoizedProps: null,         // Last rendered props
  memoizedState: null,         // Last rendered state (e.g., Hooks or state)
  updateQueue: null,           // Update queue
  child: null,                 // First child Fiber
  sibling: null,               // Next sibling Fiber
  return: null,                // Parent Fiber
  alternate: null,             // Corresponding node in current/workInProgress tree
  lanes: NoLanes,              // Priority lanes
  effectTag: NoEffect,         // Side effect tag
  firstEffect: null,           // Head of side effect linked list
  lastEffect: null,            // Tail of side effect linked list
  nextEffect: null             // Next side effect node
};

Key Field Analysis

  • tag: Identifies node type (e.g., ClassComponent, HostComponent).
  • stateNode: Points to the real DOM for DOM nodes or instance for class components.
  • alternate: Links to the corresponding node in the other tree (double buffering).
  • lanes: Priority, based on the Lane model.
  • effectTag: Marks side effects (e.g., Placement, Update).

Double Buffering Mechanism

React maintains two Fiber trees:

  • current tree: Reflects the current UI on the screen.
  • workInProgress tree: Built during the render phase.

After rendering, the workInProgress tree becomes the new current tree:

root.current = finishedWork;

Fiber Tree’s Linked-List Structure

Fiber converts the component tree from a recursive structure to a linked list:

  • child: Points to the first child node.
  • sibling: Points to the next sibling node.
  • return: Points to the parent node.

Example

<div>
  <span>A</span>
  <span>B</span>
</div>

Corresponding Fiber tree:

Fiber(div)
  ├── child: Fiber(span "A")
  │    ├── sibling: Fiber(span "B")
  │    └── return: Fiber(div)
  └── return: FiberRoot

Fiber Workflow

Fiber’s work is divided into two phases: Render Phase and Commit Phase.

Render Phase

The render phase builds the workInProgress tree and is interruptible.

Main Loop: workLoop

function workLoop(deadline) {
  let shouldYield = false;
  while (nextUnitOfWork && !shouldYield) {
    nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
    shouldYield = deadline.timeRemaining() < 1;
  }
  if (!nextUnitOfWork && wipRoot) {
    commitRoot(wipRoot);
  }
  requestIdleCallback(workLoop);
}
  • nextUnitOfWork: The currently processed Fiber node.
  • shouldYield: Controlled by Scheduler, checks if the main thread should yield.

performUnitOfWork

function performUnitOfWork(fiber) {
  if (!fiber.stateNode) {
    fiber.stateNode = createDOM(fiber); // Create DOM
  }
  const children = fiber.type(fiber.props); // Execute component function
  reconcileChildren(fiber, children);       // Reconcile children
  return completeUnitOfWork(fiber);         // Complete current node
}

reconcileChildren

function reconcileChildren(fiber, children) {
  let previousSibling = null;
  let newFiber = null;

  children.forEach((child, index) => {
    newFiber = {
      type: child.type,
      props: child.props,
      return: fiber,
      sibling: null,
      child: null
    };
    if (index === 0) {
      fiber.child = newFiber;
    } else {
      previousSibling.sibling = newFiber;
    }
    previousSibling = newFiber;
  });
}

Commit Phase

The commit phase applies workInProgress tree changes to the DOM and is uninterruptible.

commitRoot

function commitRoot(root) {
  const finishedWork = root.finishedWork;
  commitBeforeMutationEffects(finishedWork);
  commitMutationEffects(finishedWork);
  root.current = finishedWork;
  commitLayoutEffects(finishedWork);
}

Fiber Source Code Analysis

Below, we dive into Fiber’s implementation based on React 18’s react-reconciler.

Fiber Node Creation

createFiber function (ReactFiber.js):

function createFiber(tag, pendingProps, key) {
  return {
    tag,
    key,
    pendingProps,
    props: null,
    stateNode: null,
    memoizedState: null,
    updateQueue: null,
    child: null,
    sibling: null,
    return: null,
    alternate: null,
    lanes: NoLanes,
    effectTag: NoEffect
  };
}

Example: Creating HostComponent

const fiber = createFiber(HostComponent, { id: 'my-div' }, null);
fiber.type = 'div';

beginWork: Core of Render Phase

beginWork handles Fiber node updates (ReactFiberBeginWork.js):

function beginWork(current, workInProgress, renderLanes) {
  if (current !== null) {
    const oldProps = current.memoizedProps;
    const newProps = workInProgress.pendingProps;
    if (oldProps === newProps && includesSomeLane(workInProgress.lanes, renderLanes)) {
      return bailoutOnAlreadyFinishedWork(current, workInProgress);
    }
  }

  switch (workInProgress.tag) {
    case FunctionComponent:
      return updateFunctionComponent(current, workInProgress, renderLanes);
    case HostComponent:
      return updateHostComponent(current, workInProgress, renderLanes);
    // ...
  }
}

function updateFunctionComponent(current, workInProgress, renderLanes) {
  const Component = workInProgress.type;
  const nextProps = workInProgress.pendingProps;
  const nextChildren = Component(nextProps);
  reconcileChildren(current, workInProgress, nextChildren);
  return workInProgress.child;
}

completeWork: Completing Nodes

completeWork constructs DOM and marks side effects (ReactFiberCompleteWork.js):

function completeWork(current, workInProgress) {
  switch (workInProgress.tag) {
    case HostComponent:
      if (!workInProgress.stateNode) {
        workInProgress.stateNode = document.createElement(workInProgress.type);
      }
      updateHostComponentProperties(workInProgress.stateNode, workInProgress.pendingProps);
      appendAllChildren(workInProgress.stateNode, workInProgress);
      return null;
  }
}

commitMutationEffects: Applying DOM Changes

function commitMutationEffects(root, finishedWork) {
  let nextEffect = finishedWork.firstEffect;
  while (nextEffect !== null) {
    if (nextEffect.effectTag & Placement) {
      commitPlacement(nextEffect);
    }
    if (nextEffect.effectTag & Update) {
      commitWork(nextEffect.alternate, nextEffect);
    }
    if (nextEffect.effectTag & Deletion) {
      commitDeletion(root, nextEffect);
    }
    nextEffect = nextEffect.nextEffect;
  }
}

Support for Advanced Features in Fiber

Concurrent Mode

Fiber supports priority scheduling via the Lane model:

function scheduleUpdateOnFiber(fiber, lane) {
  fiber.lanes |= lane;
  ensureRootIsScheduled(fiberRoot);
}

Hooks

Hooks’ state is stored in a linked list within memoizedState:

const hook = {
  memoizedState: 0,  // useState value
  queue: null,       // Update queue
  next: null         // Next Hook
};

Suspense

SuspenseComponent supports suspension:

if (workInProgress.memoizedState !== null) {
  throw workInProgress.memoizedState.promise;
}

In-Depth Analysis of Fiber’s Advanced Mechanisms

Error Boundaries and Fiber’s Error Handling

Role Recap

Error boundaries use componentDidCatch to catch subtree exceptions, preventing application crashes. How does Fiber support this?

Example

class ErrorBoundary extends React.Component {
  state = { hasError: false };
  static getDerivedStateFromError(error) {
    return { hasError: true };
  }
  componentDidCatch(error, info) {
    console.log(error, info);
  }
  render() {
    return this.state.hasError ? <div>Error!</div> : this.props.children;
  }
}

Source Analysis

Error handling occurs in beginWork and completeWork:

Handling Thrown Exceptions
// ReactFiberBeginWork.js
function beginWork(current, workInProgress, renderLanes) {
  try {
    switch (workInProgress.tag) {
      case ClassComponent:
        return updateClassComponent(current, workInProgress, renderLanes);
      // ...
    }
  } catch (error) {
    if (didThrowDuringRender(workInProgress)) {
      throwException(workInProgress, error);
    }
    return null;
  }
}

function throwException(fiber, error) {
  fiber.flags |= ShouldCapture; // Mark for capture
  fiber.memoizedState = { error, lane: renderLanes };
  scheduleUpdateOnFiber(fiber, renderLanes); // Reschedule
}
Error Boundary Capture
function updateClassComponent(current, workInProgress, renderLanes) {
  const instance = workInProgress.stateNode;
  if (workInProgress.flags & ShouldCapture) {
    const error = workInProgress.memoizedState.error;
    instance.componentDidCatch(error, { componentStack: getStackByFiber(workInProgress) });
    workInProgress.flags &= ~ShouldCapture;
    workInProgress.flags |= HasEffect; // Mark side effect
  }
  const nextChildren = instance.render();
  reconcileChildren(current, workInProgress, nextChildren);
  return workInProgress.child;
}

Principle Summary

  • Exception Throwing: Subtree errors are caught and marked by Fiber.
  • Upward Propagation: Errors propagate along the return chain to the nearest error boundary.
  • Re-rendering: The error boundary updates state and renders fallback UI.

Suspense Suspension and Resumption

Role Recap

Suspense handles asynchronous component or data loading. How does Fiber implement suspension?

Example

const LazyComponent = React.lazy(() => import('./Component'));

function App() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <LazyComponent />
    </Suspense>
  );
}

Source Analysis

Suspension Logic
function updateSuspenseComponent(current, workInProgress, renderLanes) {
  const nextProps = workInProgress.pendingProps;
  const nextState = workInProgress.memoizedState;

  if (nextState !== null && !includesSomeLane(renderLanes, nextState.lane)) {
    // Subtree incomplete, suspend
    workInProgress.lanes = nextState.lane;
    workInProgress.flags |= DidCapture;
    return null; // Interrupt rendering
  }

  const nextChildren = nextProps.children;
  reconcileChildren(current, workInProgress, nextChildren);
  return workInProgress.child;
}
Lazy Component Promise Throwing
function updateLazyComponent(current, workInProgress, renderLanes) {
  const payload = workInProgress.pendingProps;
  if (payload._result === null) {
    const promise = payload._promise;
    promise.then(
      resolved => {
        payload._result = resolved;
        scheduleUpdateOnFiber(workInProgress, renderLanes);
      },
      error => {
        payload._result = error;
        throw error;
      }
    );
    throw promise; // Throw Promise, trigger suspension
  }
  return updateFunctionComponent(current, workInProgress, payload._result);
}
Resumption
function completeWork(current, workInProgress) {
  if (workInProgress.tag === SuspenseComponent && workInProgress.memoizedState === null) {
    // Subtree complete, clear suspension state
    return null;
  }
}

Principle Summary

  • Suspension: Child components throw Promises, Suspense Fiber marks DidCapture.
  • Resumption: After Promise resolution, rendering is rescheduled.

Lane Model’s Dynamic Scheduling Optimization

Lane Dynamic Allocation

function requestUpdateLane(fiber) {
  const mode = fiber.mode;
  if ((mode & ConcurrentMode) === NoMode) {
    return SyncLane; // Synchronous mode
  }
  const schedulerPriority = getCurrentPriorityLevel();
  return laneToLanePriority(schedulerPriority); // Allocate based on context
}

Example: TransitionLane

function startTransition(callback) {
  const fiber = currentlyRenderingFiber;
  scheduleUpdateOnFiber(fiber, TransitionLane);
  callback();
}

Source Analysis

function scheduleUpdateOnFiber(fiber, lane) {
  const root = markUpdateLaneFromFiberToRoot(fiber, lane);
  root.pendingLanes |= lane;
  ensureRootIsScheduled(root);
}

function ensureRootIsScheduled(root) {
  const highestLane = getHighestPriorityLane(root.pendingLanes);
  if (highestLane === NoLane) return;

  const existingCallback = root.callbackNode;
  if (existingCallback !== null && highestLane !== SyncLane) {
    cancelCallback(existingCallback); // Cancel lower-priority tasks
  }
  scheduleCallback(laneToSchedulerPriority(highestLane), () => performConcurrentWorkOnRoot(root));
}

Principle Summary

  • Dynamic Adjustment: High-priority tasks can interrupt lower-priority ones.
  • Lane Merging: Efficiently manages priorities via bit operations.

Deeper Details of Fiber Source Code

updateQueue Implementation

updateQueue manages state updates:

const update = {
  lane: SyncLane,      // Priority
  action: newValue,    // Update action
  next: null           // Next update
};

function appendUpdateToQueue(fiber, update) {
  const queue = fiber.updateQueue || (fiber.updateQueue = { pending: null });
  if (queue.pending === null) {
    update.next = update; // Circular linked list
  } else {
    update.next = queue.pending.next;
    queue.pending.next = update;
  }
  queue.pending = update;
}

effectTag Bit Operations

effectTag uses bit flags for side effects:

const Placement = 0b0000000000010; // Insert
const Update = 0b0000000000100;    // Update
const Deletion = 0b0000000001000;  // Delete

fiber.effectTag |= Placement | Update; // Combine flags

bailoutOnAlreadyFinishedWork Deep Optimization

function bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes) {
  if (!includesSomeLane(renderLanes, workInProgress.lanes)) {
    return null; // Not complete, don’t skip
  }
  if (current.memoizedProps === workInProgress.pendingProps) {
    cloneChildrenFromCurrent(current, workInProgress);
    return workInProgress.child; // Skip rendering
  }
  return null;
}

Fiber Performance Optimization Practices

Reducing Fiber Tree Traversal

  • Use useMemo and React.memo to avoid unnecessary updates:
const MemoizedChild = React.memo(Child);

Adjusting Time Slicing

Customize Scheduler’s yieldInterval:

const customYieldInterval = 10; // Increase slice time
function shouldYield() {
  return getCurrentTime() - startTime >= customYieldInterval;
}

Lane Priority Tuning

Prioritize user interactions:

function handleClick() {
  scheduleUpdateOnFiber(fiber, InputContinuousLane);
}

Real-World Case Studies

Case Study: Large List Rendering

function List({ items }) {
  return (
    <ul>
      {items.map(item => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
}
  • Fiber renders each <li> in chunks, avoiding blocking.

Source Debugging

function performUnitOfWork(fiber) {
  console.log('Processing:', fiber.type, fiber.key);
  // ...
}

Case Study: Suspense and Lazy

const LazyList = React.lazy(() => import('./List'));

function App() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <LazyList />
    </Suspense>
  );
}
Share your love