liveBook · Manning

Virtual DOM

As explained in Secrets of the JavaScript Ninja, Third Edition

A virtual DOM is an in-memory tree representation of a user interface that can be compared with the rendered document to determine updates.

A virtual DOM is a framework’s in-memory tree representing what a page’s DOM should look like. React uses this representation to update the page without requiring developers to manipulate DOM nodes directly. section 1.2.1 section 4.4

When component output changes, React compares the current virtual DOM with its previous version, then reconciles the difference by changing the page’s DOM. This lets application code focus on state and rendered output rather than DOM operations. section 4.4

import React, {useState} from "react";
 
function Counter() {
  const [count, setCount] = useState(0);
 
  return (
    <div>
      <div>The count is {count}.</div>
      <button
        onClick={() => {
          setCount(count + 1);
        }}
      >
        Increment count
      </button>
    </div>
  );
}

A stateful counter shows a user interaction changing component state and the rendered count. section 1.2.1

This abstraction has a startup tradeoff: JavaScript-defined pages must run code before appearing, and framework code adds work. Server-side rendering can provide the page before JavaScript runs. section 4.4

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Defines the internal tree and outlines reconciliation from comparing successive trees to DOM updates, without implementation internals.
Examples
Uses a stateful counter and an event-list component whose changing state updates rendered output.
What you can do after
Understand how React maps state-driven component output to DOM changes without direct DOM calls.
How it connects
Connects virtual DOMs to React components, JSX, DOM updates, and reconciliation.

Also explained in

Compare how 4 books explain virtual DOM →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.