Frontend Development 28 min read

Understanding Virtual DOM: Concepts, Benefits, Implementation, and Diff Algorithm in React

This article explains what the Virtual DOM is, why it improves performance, how React implements it through ReactElements and Fiber, and details the diff algorithm and reconciliation process that enable efficient UI updates in modern frontend development.

ByteFE
ByteFE
ByteFE
Understanding Virtual DOM: Concepts, Benefits, Implementation, and Diff Algorithm in React

What is Virtual DOM?

In the early days of front‑end development, pages were static and developers manipulated the real DOM directly using libraries like jQuery. Modern frameworks such as Angular and React introduced a declarative, state‑driven approach where the UI is described by data, and the framework updates the DOM automatically. The Virtual DOM concept, popularized by React, represents an in‑memory tree of JavaScript objects that mirrors the real DOM.

Virtual DOM is a programming concept where the UI is kept in an idealized, "virtual" representation in memory and synchronized with the real DOM via libraries like ReactDOM. This process is called reconciliation.
This approach gives React a declarative API: you describe the desired UI state, and React ensures the DOM matches that state, freeing you from manual DOM updates.

Key points about Virtual DOM:

It is not a real DOM; it has no direct relationship with the browser's native DOM.

It is essentially a JavaScript object that maps the view to the application state at a specific moment.

Each Virtual DOM node corresponds one‑to‑one with a real DOM node's attributes.

Developers work with state only; the framework handles DOM manipulation.

Why Use Virtual DOM?

Direct DOM operations are expensive and can cause UI jank. Virtual DOM was created to mitigate these performance issues.

DOM Operations Are Costly

DOM is not part of JavaScript; it is provided by the browser environment. The browser creates wrapper objects that map native DOM nodes to JavaScript objects. When JavaScript modifies DOM properties while the rendering thread runs, the two threads must be mutually exclusive, causing context switches and performance penalties. Additionally, many DOM API calls trigger layout recalculations (repaint and reflow), further increasing cost.

Therefore, reducing unnecessary DOM API calls is essential for performance.

Advantages of Virtual DOM

Virtual DOM does not make raw DOM manipulation faster than hand‑optimized code, but it provides a declarative programming model, batching, and diffing that reduce the number of actual DOM updates.

React creates a new Virtual DOM tree on each state change, diffs it against the previous tree, and generates a patch that updates only the changed nodes. Batching merges multiple changes into a single update, minimizing layout work.

Key benefits:

Enables functional UI programming without manual DOM handling.

Reduces the number of render passes, improving efficiency.

Provides cross‑platform capabilities because the Virtual DOM is just a JavaScript object.

How Virtual DOM Is Implemented

React treats the Virtual DOM as a pattern rather than a separate technology. It consists of ReactElements and Fiber objects.

ReactElement

A ReactElement is a plain JavaScript object that describes a DOM node or component instance. JSX like const element = <h1 id="hello">Hello, world</h1>; is compiled to React.createElement("h1", {id: "hello"}, "Hello, world") , which returns an object such as:

{
  type: 'h1',
  props: {
    id: 'hello',
    children: 'Hello, world'
  }
}

Custom components are also represented as ReactElements, and the tree of elements forms the basis for the Fiber tree.

ReactElement Source Code (simplified)

function ReactElement(type, key, ref, self, source, owner, props) {
  return {
    $$typeof: REACT_ELEMENT_TYPE,
    type,
    key,
    ref,
    props,
    _owner: owner
  };
}

function createElement(type, config, ...children) {
  const props = {};
  let key = null;
  let ref = null;
  // extract key and ref from config
  // copy remaining properties to props
  // handle children
  return ReactElement(type, key, ref, null, null, ReactCurrentOwner.current, props);
}

The resulting object contains $$typeof, key, ref, props, and a reference to the owning Fiber.

Fiber

Fiber is the internal data structure that represents a unit of work. Each Fiber node stores the type, key, a reference to the real DOM node (stateNode), and links to parent (return), first child (child), and next sibling (sibling). The Fiber tree is built from ReactElements.

React maintains two Fiber trees: the current tree that is rendered on screen and a work‑in‑progress tree that is built during reconciliation. After the work‑in‑progress tree is complete, the pointers are swapped, enabling double‑buffering and reducing memory allocation.

currentFiber.alternate === workInProgressFiber;
workInProgressFiber.alternate === currentFiber;

Reconciliation (Stack vs. Fiber)

Older versions used a stack reconciler that performed a single, non‑interruptible pass. The modern Fiber reconciler introduces a Scheduler that assigns priorities, allowing work to be paused, resumed, or aborted.

Scheduler : decides which updates run first based on priority.

Reconciler : compares the new Virtual DOM with the previous Fiber tree to produce a new work‑in‑progress tree.

Renderer : commits the changes to the real DOM.

Diff Algorithm

When render() is called, React creates a new tree of ReactElements. On the next update, it diffs the new tree against the previous one. The diff process works level‑by‑level, only comparing siblings, and uses the key prop to identify stable elements.

React’s heuristic algorithm runs in O(n) time by assuming:

Only same‑level nodes are compared; nodes that change depth are recreated.

Different element types produce different sub‑trees.

Keys help preserve element identity across renders.

For a list without keys, React will recreate every child. With keys, it can match existing nodes and only move or insert the necessary ones.

// before update
Duke
Villanova
// after update
Connecticut
Duke
Villanova

Single‑Node Diff

When diffing a single element, React checks the key first, then the type. If both match, the existing Fiber can be reused; otherwise, the old Fiber is deleted and a new one is created.

function reconcileSingleElement(returnFiber, currentFirstChild, element) {
  const key = element.key;
  let child = currentFirstChild;
  while (child !== null) {
    if (child.key === key) {
      if (child.elementType === element.type) {
        return existing; // reuse
      }
      break; // same key but different type → delete
    } else {
      deleteChild(returnFiber, child);
    }
    child = child.sibling;
  }
  // create new Fiber …
}

Multi‑Node Diff

When children are an array, React uses reconcileChildrenArray . It first tries to match nodes by key and type, marking updates, insertions (Placement), and deletions. The algorithm performs two passes: the first handles updates, the second handles remaining insertions or deletions.

After all nodes are processed and marked, the work‑in‑progress Fiber tree is handed to the Renderer for committing.

Summary

Initial render creates ReactElements from JSX, which are turned into a Fiber tree.

State changes trigger the Scheduler, which prioritizes updates.

The Reconciler diffs the new Virtual DOM against the previous Fiber tree, producing a new work‑in‑progress tree.

The Renderer commits the patches to the real DOM.

References

[1] Yu Yu Xi’s answer on Virtual DOM advantages – https://www.zhihu.com/question/31809713/answer/53544875

[2] React Elements – https://zh-hans.reactjs.org/docs/rendering-elements.html

[3] Reconciliation – https://reactjs.org/docs/reconciliation.html

[4] Fiber vs. Stack demo – https://claudiopro.github.io/react-fiber-vs-stack-demo/

[5] createFiberFromTypeAndProps source – https://github.com/facebook/react/blob/…/ReactFiber.js#L414

[6] State‑of‑the‑art diff algorithms – http://grfia.dlsi.ua.es/ml/algorithms/references/editsurvey_bille.pdf

PerformancereactVirtual DOMFiberDiff Algorithm
ByteFE
Written by

ByteFE

Cutting‑edge tech, article sharing, and practical insights from the ByteDance frontend team.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.