Virtual DOM Diff Algorithm
React Core Components Analysis
React’s Core Components
React’s core consists of the following key modules (based on React 18.x source code):
react: Core API, providing functions likeReact.createElement.react-dom: DOM rendering logic, responsible for converting virtual DOM to real DOM.react-reconciler: Reconciler, handles component tree updates and Diff algorithm.
React.createElement
- Source Location:
packages/react/src/ReactElement.js - Role: Creates React elements (virtual DOM nodes).
- Key Code:
// packages/react/src/ReactElement.js (simplified)
export function createElement(type, config, children) {
const props = {};
let key = null;
let ref = null;
if (config != null) {
if (config.key !== undefined) key = '' + config.key;
if (config.ref !== undefined) ref = config.ref;
for (const propName in config) {
if (propName !== 'key' && propName !== 'ref') {
props[propName] = config[propName];
}
}
}
const childrenLength = arguments.length - 2;
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
props.children = Array.prototype.slice.call(arguments, 2);
}
return {
$$typeof: Symbol.for('react.element'),
type,
key,
ref,
props,
};
}- Analysis:
- Input: Component type (
type), properties (config), children (children). - Output: Virtual DOM object containing
type(e.g.,'div'or function component),props, etc.
- Input: Component type (
ReactDOM.render
- Source Location:
packages/react-dom/src/client/ReactDOMLegacy.js - Role: Triggers component rendering.
- Key Code:
// packages/react-dom/src/client/ReactDOMLegacy.js (simplified)
export function render(element, container) {
const root = createRoot(container);
root.render(element);
return getPublicRootInstance(root);
}- Analysis: Invokes the reconciler to render virtual DOM to real DOM.
react-reconciler
- Source Location:
packages/react-reconciler - Role: Coordinates component tree updates, executes Diff algorithm.
- Key Logic: Manages Fiber tree (see below).
Fiber Architecture
React 16 introduced the Fiber architecture, replacing the previous stack-based reconciliation:
- Fiber Node:
// packages/react-reconciler/src/ReactFiber.js (pseudocode)
function FiberNode(tag, key) {
this.tag = tag; // Node type (e.g., HostComponent, FunctionComponent)
this.key = key; // Unique identifier
this.stateNode = null; // Real DOM or component instance
this.child = null; // Child node
this.sibling = null; // Sibling node
this.return = null; // Parent node
this.pendingProps = null; // New props
this.memoizedProps = null;// Current props
}- Role:
- Decomposes component tree into a linked-list structure.
- Supports task slicing (asynchronous rendering).
Virtual DOM and Diff Algorithm
Virtual DOM Introduction
Virtual DOM is a core concept in React:
- Definition: Lightweight in-memory representation of the DOM.
- Example:
const element = React.createElement('div', { id: 'app' }, 'Hello');
// Output:
{
$$typeof: Symbol.for('react.element'),
type: 'div',
props: { id: 'app', children: 'Hello' },
}- Advantages:
- Batch updates: Reduces direct DOM operations.
- Cross-platform: Supports React Native, etc.
Diff Algorithm Analysis
React’s Diff algorithm runs under the Fiber architecture, primarily implemented in react-reconciler. Its goal is to compute the minimal update path by comparing new and old virtual DOM.
Source Location
packages/react-reconciler/src/ReactFiberWorkLoop.js: Rendering loop.packages/react-reconciler/src/ReactFiberBeginWork.js: Diff logic.
Diff Algorithm Steps
- Single Node Diff
- Logic:
- If node type (
type) differs, replace entirely. - If type is the same, reuse node, update
props.
- If node type (
- Source (simplified):
// packages/react-reconciler/src/ReactFiberBeginWork.js
function updateHostComponent(current, workInProgress) {
const oldProps = current.memoizedProps;
const newProps = workInProgress.pendingProps;
if (oldProps !== newProps) {
// Update DOM properties
markUpdate(workInProgress);
}
return null; // No child nodes to process
}- Example:
// Old virtual DOM
<div id="old">Text</div>
// New virtual DOM
<div id="new">Text</div>
// Result: Update id property- Multi-Node Diff (List Diff)
- Prerequisite: React assumes list node order is relatively stable.
- Steps:
- Same-Level Comparison: Compares nodes at the same level only.
- Key Optimization: Uses
keyproperty for quick matching. - Two-End Comparison: Compares from both ends to reduce traversal.
- Source (simplified):
// packages/react-reconciler/src/ReactChildFiber.js
function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren) {
let resultingFirstChild = null;
let previousNewFiber = null;
let oldFiber = currentFirstChild;
let newIdx = 0;
// First pass: Reuse nodes with same key
while (oldFiber !== null && newIdx < newChildren.length) {
if (oldFiber.key === newChildren[newIdx].key) {
const newFiber = useFiber(oldFiber, newChildren[newIdx].props);
if (previousNewFiber === null) {
resultingFirstChild = newFiber;
} else {
previousNewFiber.sibling = newFiber;
}
previousNewFiber = newFiber;
}
oldFiber = oldFiber.sibling;
newIdx++;
}
// Second pass: Process remaining nodes
while (newIdx < newChildren.length) {
const newFiber = createFiber(newChildren[newIdx]);
if (previousNewFiber === null) {
resultingFirstChild = newFiber;
} else {
previousNewFiber.sibling = newFiber;
}
previousNewFiber = newFiber;
newIdx++;
}
return resultingFirstChild;
}- Example:
// Old virtual DOM
[<li key="1">A</li>, <li key="2">B</li>]
// New virtual DOM
[<li key="2">B</li>, <li key="1">A</li>]
// Result: Adjust order, no deletion/recreation- Conditions and Optimizations
- Single-Type Assumption: Highest efficiency when nodes at the same level are of the same type.
- Key’s Role: Enables quick positioning via
key, avoiding full comparison. - Sliced Updates: Fiber architecture allows Diff to be interrupted and executed asynchronously.
Diff Algorithm Efficiency Analysis
- Time Complexity:
- Without
key: O(n³) (traditional DOM comparison). - With
key: O(n) (linear comparison).
- Without
- Space Complexity: O(n) (storing Fiber tree).
Update Process
- Create New Fiber Tree
- Starts from the root, builds a new Fiber tree based on the new virtual DOM.
- Diff Comparison
- Compares new and old Fiber, marking updates, insertions, or deletions.
- Commit Updates
commitphase applies changes to the real DOM:
// packages/react-dom/src/client/ReactDOMHostConfig.js (pseudocode)
function commitUpdate(fiber) {
const { stateNode, memoizedProps, pendingProps } = fiber;
for (const key in pendingProps) {
stateNode[key] = pendingProps[key];
}
}Comprehensive Practice and Analysis
Example Project
App.jsx:
import React, { useState } from 'react';
function App() {
const [items, setItems] = useState(['A', 'B']);
const addItem = () => setItems([...items, 'C']);
return (
<div>
<button onClick={addItem}>Add</button>
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
</div>
);
}- Issue: Using
indexaskeymay lead to inefficient Diff. - Optimization:
<li key={item}>{item}</li>Debugging Diff Algorithm
- Add Logging
- Modify
ReactFiberBeginWork.js:
function beginWork(current, workInProgress) {
console.log(`Diffing: ${workInProgress.type}`);
// Original logic
}- Run
- Build React and run the example, observe Diff logs.
Reconciliation Process
What is Reconciliation?
Definition and Background
Reconciliation is the process React uses to determine how to update the DOM when a component’s state or props change. React’s core philosophy is declarative programming, where developers define the desired state and props, and React handles efficiently reflecting these changes in the real DOM.
Traditional DOM operations are costly (e.g., frequent reflows and repaints). React introduces Virtual DOM, abstracting updates as in-memory operations. The reconciliation process computes the optimal DOM update strategy, significantly improving performance.
Virtual DOM Introduction
Virtual DOM is a lightweight representation of the real DOM, essentially a JavaScript object tree. Each time the state changes, React generates a new virtual DOM tree, compares it with the previous one (Diff algorithm), identifies updates, and applies them to the real DOM.
For example, a simple React component:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}In memory, React converts it to a virtual DOM object:
{
type: 'h1',
props: { children: ['Hello, ', 'Alice'] }
}Reconciliation Goals
The reconciliation process aims to:
- Efficiency: Minimize direct DOM operations.
- Consistency: Keep UI in sync with state.
- Predictability: Free developers from manual DOM update logic.
Reconciliation Workflow
Reconciliation consists of two main phases: Render Phase and Commit Phase. With the introduction of the Fiber architecture, this process is more modular and interruptible, but the core logic revolves around virtual DOM Diff and updates.
Render Phase
The render phase generates a new virtual DOM tree. Whenever state or props change, React re-invokes the component’s render function to create a new virtual DOM tree.
Example Code
Consider this component:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}When the button is clicked, count updates, and React re-invokes Counter, generating a new virtual DOM tree.
Initial virtual DOM:
{
type: 'div',
props: {
children: [
{ type: 'p', props: { children: 'You clicked 0 times' } },
{ type: 'button', props: { onClick: fn, children: 'Click me' } }
]
}
}Updated virtual DOM:
{
type: 'div',
props: {
children: [
{ type: 'p', props: { children: 'You clicked 1 times' } },
{ type: 'button', props: { onClick: fn, children: 'Click me' } }
]
}
}Diff Algorithm: Comparing New and Old Virtual DOM
After the render phase, React enters the Diff process, comparing new and old virtual DOM trees to identify updates. The Diff algorithm is the core of reconciliation, optimized by React’s assumptions and strategies.
Diff Algorithm’s Three Principles
- Same-Level Comparison: Compares nodes at the same level only, not across levels.
- Type Check: If node types differ (e.g.,
divtospan), React destroys the old node and creates a new one. - Key Optimization: Uses
keyproperty to quickly identify list node identities, avoiding unnecessary recreations.
Code Analysis: Diff Process
Consider this update:
Old tree:
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>New tree:
<ul>
<li>Item 1</li>
<li>Item 3</li>
</ul>React will:
- Compare
<ul>node, find same type, proceed deeper. - Compare
<li>children:- First
<li>unchanged, reuse. - Second
<li>changed to “Item 3”, update text content.
- First
Virtual DOM Diff result:
- Update the second
<li>’s text node.
Commit Phase
After Diff, React enters the commit phase, applying calculated changes to the real DOM. This phase is synchronous to ensure UI update consistency.
Example: Real DOM Update
For the above example, React performs operations like:
document.querySelector('li:nth-child(2)').textContent = 'Item 3';Deep Dive into Diff Algorithm Implementation Details
React’s Diff algorithm appears simple but includes numerous optimizations. Let’s break down its implementation via code.
Single Node Diff
For a single node, React checks:
- Same Type: If types differ, replace.
- Property Changes: If properties change, update.
- Child Changes: Recursively compare children.
Example Code
Old node:
<div className="old">Hello</div>New node:
<div className="new">Hello</div>Diff process pseudocode:
function diffNode(oldNode, newNode) {
if (oldNode.type !== newNode.type) {
return { type: 'REPLACE', newNode };
}
const propsChanges = diffProps(oldNode.props, newNode.props);
const childChanges = diffChildren(oldNode.children, newNode.children);
return { type: 'UPDATE', propsChanges, childChanges };
}
function diffProps(oldProps, newProps) {
const changes = {};
for (let key in newProps) {
if (oldProps[key] !== newProps[key]) {
changes[key] = newProps[key];
}
}
return changes;
}Result: Update className property.
List Diff and Role of Key
For lists, React relies on the key property to optimize Diff. Without key, React compares sequentially, potentially causing excessive updates.
Example: List Without Key
Old list:
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>New list (insert one element):
<ul>
<li>Item 0</li>
<li>Item 1</li>
<li>Item 2</li>
</ul>Without key, React assumes every node changed, updating all.
Example: List With Key
Old list:
<ul>
<li key="1">Item 1</li>
<li key="2">Item 2</li>
</ul>New list:
<ul>
<li key="0">Item 0</li>
<li key="1">Item 1</li>
<li key="2">Item 2</li>
</ul>With key, React:
- Matches nodes by
key, findskey="1"andkey="2"unchanged. - Inserts
key="0"node only.
Pseudocode:
function diffList(oldChildren, newChildren) {
const map = new Map();
oldChildren.forEach(child => map.set(child.key, child));
const changes = [];
newChildren.forEach((newChild, index) => {
const oldChild = map.get(newChild.key);
if (!oldChild) {
changes.push({ type: 'INSERT', node: newChild, index });
} else if (!isEqual(oldChild, newChild)) {
changes.push({ type: 'UPDATE', node: newChild, index });
}
});
return changes;
}Reconciliation Under Fiber Architecture
React 16’s Fiber architecture breaks reconciliation into interruptible tasks. Each Fiber node represents a work unit, allowing React to pause, resume, or abort tasks.
Fiber Node Structure
const fiber = {
type: 'div', // Node type
props: { children: [] }, // Properties
child: null, // First child node
sibling: null, // Next sibling node
return: null, // Parent node
stateNode: null // Corresponding real DOM
};Time Slicing
React schedules tasks via requestIdleCallback (or polyfill):
function workLoop(deadline) {
while (nextUnitOfWork && deadline.timeRemaining() > 0) {
nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
}
if (!nextUnitOfWork) {
commitRoot();
} else {
requestIdleCallback(workLoop);
}
}Practical Techniques for Optimizing Reconciliation
Optimize Lists with Key
Always provide unique and stable key for list items, avoiding indices as key.
Component Splitting and Memo
Use React.memo to prevent unnecessary re-renders:
const Item = React.memo(({ value }) => <li>{value}</li>);shouldComponentUpdate and useMemo
Customize shouldComponentUpdate in class components or use useMemo in function components to control rendering.
SuspenseList Implementation Principle and Source Analysis
SuspenseList is an experimental React component (not fully stable as of React 18), designed to coordinate the loading order of multiple Suspense components, preventing UI flickering or inconsistent experiences due to varying async operation completion times. This section dissects its implementation from principle to source code.
SuspenseList Introduction
What is SuspenseList?
SuspenseList is a React component that wraps multiple Suspense components, controlling their display order via the revealOrder prop. It addresses issues where async components (e.g., data fetching or code splitting) complete at different times, causing UI “jumps” or disordered rendering.
Example Scenario
Consider this code:
function App() {
return (
<>
<Suspense fallback={<div>Loading 1...</div>}>
<Component1 /> {/* Takes 2 seconds to load */}
</Suspense>
<Suspense fallback={<div>Loading 2...</div>}>
<Component2 /> {/* Takes 1 second to load */}
</Suspense>
</>
);
}Without SuspenseList, Component2 may render before Component1, causing UI jumps. With SuspenseList, rendering follows a defined order:
function App() {
return (
<SuspenseList revealOrder="forwards">
<Suspense fallback={<div>Loading 1...</div>}>
<Component1 />
</Suspense>
<Suspense fallback={<div>Loading 2...</div>}>
<Component2 />
</Suspense>
</SuspenseList>
);
}Here, even if Component2 loads first, it waits for Component1 to render sequentially.
Core Properties
revealOrder:forwards: Displays from top to bottom.backwards: Displays from bottom to top.together: Displays all components together after all load.
tail(optional):collapsed: Shows fallback for unloaded components.hidden: Hides fallback for unloaded components.
SuspenseList Working Principle
SuspenseList relies on React’s Fiber architecture and context mechanism, coordinating multiple Suspense components via:
- Tracking Child States: Records whether each
Suspensehas finished loading (“revealed”). - Context Propagation: Passes control info to child
SuspenseviaSuspenseContext. - Rendering Decisions: Determines when to show content or fallback based on
revealOrderand child states.
In the Fiber architecture, each React component is a Fiber node. SuspenseList, as a Fiber node, manages its subtree’s rendering logic, modifying context to instruct child Suspense components whether to delay display, even if their async operations are complete.
Source Analysis
Let’s dive into React’s source code (based on react-reconciler, React 18 experimental implementation) to analyze SuspenseList’s logic.
SuspenseList Fiber Node Creation
SuspenseList’s Fiber node type is SuspenseListComponent, identified and processed during reconcileChildren:
// react-reconciler/src/ReactChildFiber.js
function reconcileChildFibers(returnFiber, currentFirstChild, newChild) {
if (newChild.type === REACT_SUSPENSE_LIST_TYPE) {
return reconcileSuspenseList(returnFiber, currentFirstChild, newChild);
}
// ...other logic
}reconcileSuspenseList creates a Fiber node for SuspenseList and initializes its state.
SuspenseContext Definition
SuspenseContext is defined in react-reconciler/src/ReactFiberSuspenseContext.js:
const suspenseStackCursor = createCursor(defaultSuspenseContext);
function pushSuspenseContext(fiber, context) {
push(suspenseStackCursor, context, fiber);
}
function popSuspenseContext(fiber) {
pop(suspenseStackCursor, fiber);
}defaultSuspenseContext: Initial value (typically 0).ForceSuspenseFallback(e.g.,0x1): Flag to force fallback display.
SuspenseList Rendering Logic
During completeWork, SuspenseList checks child loading states and updates context:
// react-reconciler/src/ReactFiberCompleteWork.js
function completeWork(current, workInProgress) {
switch (workInProgress.tag) {
case SuspenseListComponent:
return completeSuspenseList(workInProgress);
// ...
}
}
function completeSuspenseList(workInProgress) {
const children = workInProgress.child;
let hasSuspended = false;
let tail = null;
// Iterate children, check for unloaded Suspense
let child = children;
while (child !== null) {
if (child.tag === SuspenseComponent && child.memoizedState !== null) {
hasSuspended = true;
if (!tail) tail = child; // Record first incomplete node
}
child = child.sibling;
}
// Adjust context based on revealOrder
if (hasSuspended) {
pushSuspenseContext(workInProgress, ForceSuspenseFallback);
} else {
popSuspenseContext(workInProgress);
}
return null;
}- If an unloaded
Suspenseexists (memoizedState !== nullindicates suspended),SuspenseListsetsForceSuspenseFallback, forcing subsequent nodes to stay in fallback. tailtracks the start of incomplete nodes fortail="collapsed"orhiddenhandling.
Child Suspense Decision Logic
Child Suspense components read SuspenseContext during rendering:
function completeSuspense(current, workInProgress) {
const suspenseContext = suspenseStackCursor.current;
const didSuspend = workInProgress.memoizedState !== null;
if (didSuspend) {
// If suspended, show fallback
return bubbleProperties(workInProgress);
} else if (suspenseContext & ForceSuspenseFallback) {
// If context forces fallback, show fallback even if complete
return bubbleProperties(workInProgress);
} else {
// Show content
return null;
}
}- When
ForceSuspenseFallbackis set,Suspenseshows fallback even if loaded, enabling sequential control.
Commit Phase
In the commit phase, React updates the DOM based on SuspenseList’s computed results, ensuring display follows revealOrder.
RevealOrder Specific Implementation
forwards
- Checks from the first child.
- If the first
Suspenseis incomplete, subsequent nodes stay in fallback until it completes. - Proceeds to the next after completion.
backwards
- Checks from the last child.
- If the last is incomplete, preceding nodes stay in fallback.
together
- Displays all
Suspensecomponents together after all complete. - In
completeWork, if any child is suspended, setsForceSuspenseFallback.
Design Trade-offs and Limitations
Why Context?
Since the Fiber tree is unidirectional (parent to child, child to sibling), SuspenseList cannot directly access sibling states, relying on ancestral context for coordination.
Limitations
- Direct Children Only:
SuspenseListcontrols only immediate childSuspense, not nested ones. - Experimental: Implementation may change, use cautiously in production.
render() Analysis
In React, render() is the core method for component rendering. Whether in class or function components, render() (or its equivalent) converts component logic into UI descriptions. This section analyzes render() from multiple angles, including source code.
render() Basic Concepts
Definition
render() is a lifecycle method in React class components, returning React elements (typically JSX) describing the UI. React uses these to generate virtual DOM and update the real DOM.
Example: render() in Class Component
import React from 'react';
class MyComponent extends React.Component {
render() {
return <div>Hello, {this.props.name}</div>;
}
}
export default MyComponent;Here, render() returns a React element, converted to virtual DOM by React.
Equivalent in Function Components
Function components lack an explicit render() method, but their return value serves the same purpose:
function MyComponent({ name }) {
return <div>Hello, {name}</div>;
}React treats the function’s return as render() output.
Role
- Generate UI Description:
render()doesn’t manipulate DOM directly, returning a virtual DOM blueprint. - Declarative: Developers focus on “what” the UI is, not “how” to update DOM.
- Pure Function:
render()should avoid side effects (e.g., state changes or DOM manipulation) for predictability.
render() in Lifecycle
Class Component Lifecycle
In class components, render() is a key lifecycle part, called during:
- Initial Rendering (Mounting):
constructor()static getDerivedStateFromProps()render()componentDidMount()
- Updates (Updating):
static getDerivedStateFromProps()shouldComponentUpdate()(skipsrender()iffalse)render()getSnapshotBeforeUpdate()componentDidUpdate()
Example: render() on Update
class Counter extends React.Component {
state = { count: 0 };
handleClick = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
console.log('Rendering...');
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.handleClick}>Increment</button>
</div>
);
}
}Each button click triggers setState, invoking render() to generate a new virtual DOM.
Function Component Equivalent
In function components, state changes (e.g., via useState) cause the function to re-execute, equivalent to calling render().
render() Working Principle
From JSX to Virtual DOM
render()’s JSX return is compiled into React.createElement() calls, generating virtual DOM. For example:
render() {
return <div>Hello</div>;
}Compiled to:
render() {
return React.createElement('div', null, 'Hello');
}Generated virtual DOM:
{
type: 'div',
props: { children: 'Hello' },
key: null,
ref: null
}Trigger Timing
render() is invoked when:
- Component mounts initially.
- State changes via
setState()oruseStateupdates. - Props change from parent.
- Forced update via
forceUpdate().
Performance Optimization
React uses shouldComponentUpdate() (class components) or React.memo (function components) to skip render() and avoid unnecessary re-renders.
Example: shouldComponentUpdate
class MyComponent extends React.Component {
shouldComponentUpdate(nextProps) {
return nextProps.name !== this.props.name;
}
render() {
console.log('Rendering...');
return <div>{this.props.name}</div>;
}
}If name is unchanged, render() is skipped.
render() Under Fiber Architecture
React 16’s Fiber architecture splits render() execution into granular tasks. Let’s analyze it with source code.
Fiber Nodes and render()
Each component maps to a Fiber node. render() executes in the Render Phase, building or updating the Fiber tree.
Fiber Node Structure
const fiber = {
tag: ClassComponent, // Component type (e.g., class, function)
type: MyComponent, // Component constructor
stateNode: instance, // Component instance
memoizedState: null, // State
updateQueue: null, // Update queue
child: null, // Child Fiber
sibling: null, // Sibling Fiber
return: null // Parent Fiber
};render() Call Process
- beginWork: Traverses Fiber tree, calls
render()to generate subtree.
// react-reconciler/src/ReactFiberBeginWork.js
function beginWork(current, workInProgress) {
switch (workInProgress.tag) {
case ClassComponent:
return updateClassComponent(current, workInProgress);
case FunctionComponent:
return updateFunctionComponent(current, workInProgress);
// ...
}
}
function updateClassComponent(current, workInProgress) {
const instance = workInProgress.stateNode;
if (instance === null) {
// Initial mount
instance = workInProgress.stateNode = new workInProgress.type();
}
const newProps = workInProgress.pendingProps;
const oldProps = current !== null ? current.memoizedProps : null;
// Call render()
const children = instance.render();
reconcileChildren(workInProgress, children);
return workInProgress.child;
}- For class components,
render()is called from the instance. - For function components, the function is executed directly.
- reconcileChildren: Converts
render()output to child Fiber nodes.
function reconcileChildren(workInProgress, children) {
const isObject = typeof children === 'object' && children !== null;
if (isObject && children.$$typeof === REACT_ELEMENT_TYPE) {
// Single node
mountChildFibers(workInProgress, children);
} else if (Array.isArray(children)) {
// List
reconcileChildFibers(workInProgress, children);
}
}- completeWork: Finalizes Fiber node construction, prepares for commit.
function completeWork(current, workInProgress) {
// Handle props, ref, etc.
return null;
}Time Slicing
Fiber allows render() to be interrupted. React schedules via Scheduler:
function workLoop(deadline) {
while (nextUnitOfWork && deadline.timeRemaining() > 0) {
nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
}
if (nextUnitOfWork) {
scheduleCallback(workLoop);
} else {
commitRoot();
}
}If time runs out, render() pauses, resuming when idle.
Common Issues and Optimizations
Why Doesn’t render() Update DOM Directly?
render() generates virtual DOM; actual DOM updates occur in the commit phase. This separation boosts performance and supports async rendering.
Avoiding Frequent render()
- PureComponent: Auto shallow-compares
propsandstate. - React.memo: Equivalent for function components.
- useMemo/useCallback: Cache results or functions to reduce child re-renders.
Example: useMemo
function ExpensiveComponent({ data }) {
const computed = useMemo(() => expensiveCalculation(data), [data]);
return <div>{computed}</div>;
}commit() Process Analysis
React’s rendering splits into Render Phase and Commit Phase. The commit phase synchronizes in-memory results (Fiber tree changes) to the real DOM. Unlike the interruptible render phase, commit is synchronous to ensure UI consistency. This section dissects the commit phase from overview to source details.
Commit Phase Overview
Definition and Role
The commit phase is React’s final rendering step, with tasks:
- Update Real DOM: Executes DOM operations (insert, update, delete) based on Fiber tree diffs.
- Run Side Effects: Invokes lifecycle methods (e.g.,
componentDidMount,componentDidUpdate) or hooks (e.g.,useEffect). - Clean State: Processes Fiber tree marks (effects) for the next render.
Render vs. Commit Phase
- Render Phase:
- Interruptible, sliced execution.
- Builds new Fiber tree, computes diffs.
- No direct DOM impact.
- Commit Phase:
- Synchronous, uninterruptible.
- Applies diffs to DOM, runs side effects.
- Directly affects visible UI.
Execution Timing
commit triggers when:
- Initial rendering completes.
- State or prop updates finish render phase.
- Forced updates (
forceUpdate) complete rendering.
Commit Phase Macro Workflow
In Fiber architecture, commit is driven by commitRoot, with three sub-phases:
- Before Mutation: Prepares DOM updates, runs
getSnapshotBeforeUpdate. - Mutation: Executes DOM operations (insert, update, delete).
- Layout: Post-update, runs layout-related side effects (e.g.,
componentDidMount,useLayoutEffect).
Fiber Tree “Double Buffering”
React uses “double buffering” for Fiber trees:
currenttree: Reflects current UI.workInProgresstree: Built in render phase.
Incommit,workInProgressbecomes the newcurrenttree.
Commit Phase Source Analysis
Based on React 18’s react-reconciler source, let’s analyze commit.
Entry Point: commitRoot
commit starts with commitRoot in ReactFiberWorkLoop.js:
function commitRoot(root) {
const finishedWork = root.finishedWork; // workInProgress tree
if (finishedWork === null) {
return; // No updates
}
root.finishedWork = null; // Clear mark
// First phase: Before Mutation
commitBeforeMutationEffects(root, finishedWork);
// Second phase: Mutation
commitMutationEffects(root, finishedWork);
// Switch current tree
root.current = finishedWork;
// Third phase: Layout
commitLayoutEffects(root, finishedWork);
// Schedule async side effects (e.g., useEffect)
ensureRootIsScheduled(root);
}finishedWork: CompletedworkInProgresstree from render.- Sub-phases execute sequentially.
Before Mutation Phase
Prepares DOM changes, calls getSnapshotBeforeUpdate for snapshots.
Source Snippet
function commitBeforeMutationEffects(root, finishedWork) {
nextEffect = finishedWork;
while (nextEffect !== null) {
const effectTag = nextEffect.effectTag;
if (effectTag & Snapshot) {
const current = nextEffect.alternate;
const instance = nextEffect.stateNode;
instance.getSnapshotBeforeUpdate(current.memoizedProps, current.memoizedState);
}
nextEffect = nextEffect.nextEffect;
}
}effectTag: Marks Fiber node side effect types (e.g.,Snapshot,Update).nextEffect: Links to next Fiber with side effects.
Example
class MyComponent extends React.Component {
getSnapshotBeforeUpdate(prevProps, prevState) {
return { scrollPosition: window.scrollY };
}
componentDidUpdate(prevProps, prevState, snapshot) {
console.log('Snapshot:', snapshot.scrollPosition);
}
render() {
return <div>{this.props.value}</div>;
}
}In Before Mutation, getSnapshotBeforeUpdate runs, passing its return to componentDidUpdate.
Mutation Phase
Executes real DOM operations (insert, update, delete).
Source Snippet
function commitMutationEffects(root, finishedWork) {
nextEffect = finishedWork;
while (nextEffect !== null) {
const effectTag = nextEffect.effectTag;
if (effectTag & Placement) {
commitPlacement(nextEffect); // Insert node
}
if (effectTag & Update) {
commitWork(nextEffect.alternate, nextEffect); // Update node
}
if (effectTag & Deletion) {
commitDeletion(root, nextEffect); // Delete node
}
nextEffect = nextEffect.nextEffect;
}
}commitPlacement: Inserts new nodes.
function commitPlacement(finishedWork) {
const parentFiber = getHostParent(finishedWork);
const parent = parentFiber.stateNode;
const domNode = finishedWork.stateNode;
parent.appendChild(domNode);
}commitWork: Updates properties.
function commitWork(current, finishedWork) {
const updatePayload = finishedWork.updateQueue;
if (updatePayload !== null) {
const instance = finishedWork.stateNode;
updateDOMProperties(instance, updatePayload);
}
}commitDeletion: Removes nodes, unmounts components.
function commitDeletion(root, finishedWork) {
const parent = getHostParent(finishedWork).stateNode;
const domNode = finishedWork.stateNode;
parent.removeChild(domNode);
unmountHostComponents(finishedWork); // Calls componentWillUnmount
}Example: DOM Update
From:
<div><span>Old</span></div>To:
<div><span>New</span></div>commitMutationEffects:
- Detects
span’sUpdatemark. - Calls
updateDOMPropertiesto change text from “Old” to “New”.
Layout Phase
Post-DOM update, handles layout-related side effects (e.g., componentDidMount, componentDidUpdate, useLayoutEffect).
Source Snippet
function commitLayoutEffects(root, finishedWork) {
nextEffect = finishedWork;
while (nextEffect !== null) {
const effectTag = nextEffect.effectTag;
if (effectTag & (MountLayout | Update)) {
const instance = nextEffect.stateNode;
if (nextEffect.alternate === null) {
instance.componentDidMount();
} else {
instance.componentDidUpdate(
nextEffect.alternate.memoizedProps,
nextEffect.alternate.memoizedState
);
}
}
nextEffect = nextEffect.nextEffect;
}
}MountLayout: Initial mount.Update: Triggers on updates.
Example: useLayoutEffect
function MyComponent() {
React.useLayoutEffect(() => {
console.log('Layout effect ran');
});
return <div>Hello</div>;
}In Layout, useLayoutEffect’s callback runs synchronously post-DOM update.
Async Side Effect Scheduling
useEffect side effects are scheduled, not executed, in commit:
function ensureRootIsScheduled(root) {
scheduleCallback(NormalPriority, () => {
flushSyncCallbacks(); // Run useEffect
});
}Effect List Role
commit relies on the effect list (side effect linked list) of Fiber nodes marked in render. Nodes are linked via nextEffect:
fiber.effectTag = Placement | Update; // Mark side effect
fiber.nextEffect = nextFiberWithEffect; // Link to nextcommitRoot traverses this list, efficiently processing changes.
Optimizations and Considerations
Why Synchronous?
commit involves DOM operations and side effects, requiring synchronous execution to avoid UI inconsistencies (e.g., partial updates causing flicker).
Performance Bottlenecks
Frequent DOM operations can slow performance. Optimize via:
- Reduce Renders: Use
React.memoorshouldComponentUpdate. - Batch Updates: Leverage React’s batching.
Scheduler Implementation Principle and Source Analysis
This section details React’s Scheduler, its principles, and source code. As a key Fiber architecture component, Scheduler manages task priority and time slicing for efficient async rendering. We’ll analyze it from overview to React 18’s scheduler source.
Scheduler Introduction
What is Scheduler?
Scheduler is a standalone React module (scheduler package) coordinating render phase task execution. It uses time slicing and priority scheduling to maintain responsiveness in high-load scenarios.
Example Scenario
- User typing needs immediate input updates (high priority).
- Background large data load (low priority).
Scheduler prioritizes typing, deferring data rendering to idle times.
Core Functions
- Task Priority Management: Differentiates task urgency (e.g., immediate vs. delayed).
- Time Slicing: Splits long tasks into chunks, running in browser idle time.
- Callback Scheduling: Uses
requestIdleCallbackorMessageChannelfor cross-browser compatibility.
Scheduler and Fiber
Scheduler collaborates with Fiber:
- Fiber splits rendering into small units (work).
- Scheduler determines execution timing.
Scheduler Design Principles
Priority Model
Scheduler defines five priorities (react-reconciler/src/ReactFiberLane.js):
ImmediatePriority(-1): Immediate, e.g., synchronous tasks.UserBlockingPriority(250ms timeout): User interactions, e.g., clicks.NormalPriority(5000ms timeout): Regular tasks, e.g., data updates.LowPriority(10000ms timeout): Low-priority, e.g., background tasks.IdlePriority(no fixed timeout): Idle-time tasks.
Priorities use the Lane model, a 32-bit integer for multiple task states:
const NoLanes = 0b0000000;
const ImmediateLane = 0b0000001;
const UserBlockingLane = 0b0000010;
const NormalLane = 0b0000100;Time Slicing Mechanism
Scheduler runs tasks in browser idle time, avoiding main thread blocking, using:
requestIdleCallback: Native browser API for idle tasks.MessageChannel: High-performance fallback for browsers lackingrequestIdleCallback.
Time Slicing Example
Rendering 1000 nodes takes 50ms, but browsers allow 16ms per frame (60fps). Scheduler splits into 5ms chunks, completing over idle periods.
Task Queue
Scheduler maintains a task queue, sorted by priority and expiration time:
- High-priority tasks execute first.
- Tasks nearing expiration (
expirationTime) are prioritized.
Source Analysis
Based on React 18’s scheduler/src/Scheduler.js, let’s analyze Scheduler’s implementation.
Core Data Structures
Task Object
Each task is an object:
const task = {
id: taskId++, // Unique ID
callback: workCallback, // Task function
priorityLevel: NormalPriority, // Priority
startTime: currentTime, // Creation time
expirationTime: startTime + timeout, // Expiration time
sortIndex: -1 // Sort index
};Task Queues
Scheduler uses two heap queues:
timerQueue: Delayed tasks not yet due (sorted bystartTime).taskQueue: Tasks ready to execute (sorted byexpirationTime).
const timerQueue = new MinHeap();
const taskQueue = new MinHeap();Task Scheduling Entry: scheduleCallback
scheduleCallback is Scheduler’s main external interface:
function scheduleCallback(priorityLevel, callback, options) {
const currentTime = getCurrentTime(); // Current timestamp
const startTime = options?.delay ? currentTime + options.delay : currentTime;
const timeout = getTimeoutFromPriority(priorityLevel); // Timeout from priority
const expirationTime = startTime + timeout;
const newTask = {
id: taskId++,
callback,
priorityLevel,
startTime,
expirationTime,
sortIndex: expirationTime
};
if (startTime > currentTime) {
// Delayed task to timerQueue
push(timerQueue, newTask);
if (!isHostTimeoutScheduled) {
isHostTimeoutScheduled = true;
requestHostTimeout(handleTimeout, startTime - currentTime);
}
} else {
// Immediate task to taskQueue
push(taskQueue, newTask);
if (!isHostCallbackScheduled) {
isHostCallbackScheduled = true;
requestHostCallback(flushWork);
}
}
return newTask;
}getTimeoutFromPriority: Returns timeout (e.g., 5000ms forNormalPriority).requestHostTimeout: Schedules delayed tasks (e.g.,setTimeout).requestHostCallback: Schedules immediate tasks.
Main Work Loop: flushWork
flushWork drives task execution:
function flushWork(hasTimeRemaining, initialTime) {
isHostCallbackScheduled = false;
// Move expired tasks from timerQueue to taskQueue
while (peek(timerQueue) !== null && peek(timerQueue).startTime <= initialTime) {
push(taskQueue, pop(timerQueue));
}
// Execute tasks in taskQueue
return workLoop(hasTimeRemaining, initialTime);
}Time Slicing Core: workLoop
workLoop handles time slicing:
function workLoop(hasTimeRemaining, initialTime) {
let currentTask = peek(taskQueue);
while (currentTask !== null) {
if (!hasTimeRemaining() || shouldYieldToHost()) {
// Time’s up, pause
return false;
}
const callback = currentTask.callback;
if (callback !== null) {
currentTask.callback = null; // Mark executed
const didContinue = callback(initialTime);
if (didContinue) {
// Task incomplete, return to queue
currentTask.callback = callback;
}
} else {
pop(taskQueue); // Remove completed task
}
currentTask = peek(taskQueue);
}
return true; // All tasks complete
}shouldYieldToHost: Checks if control should yield:
function shouldYieldToHost() {
const currentTime = getCurrentTime();
return currentTime - frameStartTime >= yieldInterval; // Default 5ms
}- If a task is incomplete (e.g., Fiber rendering pauses), returns
trueto reschedule.
MessageChannel Implementation
Scheduler uses MessageChannel to emulate requestIdleCallback:
const channel = new MessageChannel();
const port = channel.port2;
channel.port1.onmessage = performWorkUntilDeadline;
function requestHostCallback(callback) {
scheduledHostCallback = callback;
port.postMessage(null);
}
function performWorkUntilDeadline() {
if (scheduledHostCallback) {
const hasTimeRemaining = () => getCurrentTime() - startTime < yieldInterval;
scheduledHostCallback(hasTimeRemaining);
}
}postMessagetriggers async callbacks, bypassing event loop delays.
Scheduler Integration with React
Calls in Fiber
React schedules rendering tasks via scheduleCallback:
// ReactFiberWorkLoop.js
function ensureRootIsScheduled(root) {
const lane = root.pendingLanes;
const priority = getHighestPriorityLane(lane);
scheduleCallback(priority, () => performSyncWorkOnRoot(root));
}Rendering Task Slicing
Fiber’s workLoop collaborates with Scheduler:
function workLoopConcurrent() {
while (workInProgress !== null && !shouldYield()) {
workInProgress = performUnitOfWork(workInProgress);
}
}shouldYield is provided by Scheduler, ensuring tasks fit within time slices.
Design Trade-offs and Optimizations
Why Not setTimeout?
setTimeout has a 4ms minimum delay and lacks precision. MessageChannel offers higher-performance async scheduling.
Performance Optimizations
- Heap Queues: Min-heaps quickly fetch highest-priority tasks.
- Dynamic Adjustment:
yieldIntervaladjusts dynamically (default 5ms) based on device performance.



