~/alexsh.blog

$ cat react-internals/03-render-phase.md

Render Phase

February 9, 20261 min readpart 03/13

The render phase is where React figures out what changed. It's pure computation — no DOM mutations. This phase is interruptible in concurrent mode.

The Work Loop

codetsx
function workLoopConcurrent() {
  while (workInProgress !== null && !shouldYield()) {
    performUnitOfWork(workInProgress);
  }
}

function performUnitOfWork(unitOfWork) {
  const next = beginWork(unitOfWork);  // Process, return first child
  if (next === null) {
    completeUnitOfWork(unitOfWork);    // No children → sibling or parent
  } else {
    workInProgress = next;
  }
}

shouldYield() checks if the browser needs the main thread back (via MessageChannel). If so, React pauses and resumes later exactly where it left off.

beginWork

Called for each Fiber going down the tree. Behavior depends on the Fiber's tag: FunctionComponent → calls the function (runs hooks); ClassComponent → calls render(); HostComponent → diffs props; ContextProvider → pushes new value onto internal stack.

completeWork

Called going back up. Creates actual DOM nodes (but doesn't insert them), bubbles effect flags from children into subtreeFlags, and builds the effect list of Fibers needing DOM mutations.

The Diffing Algorithm

Instead of O(n³) general tree diff, React uses two heuristics for O(n):

Heuristic 1: Different types produce different trees — a <div> changing to <span> tears down the entire subtree.

Heuristic 2: Keys identify stable elements. For list children, React builds a Map keyed by key (or index), then walks the new list matching against it.

Why index keys are bad: inserting at the beginning shifts every index, so React thinks every element changed — causing unnecessary unmounts and lost state.

Further reading