Explaining the Virtual DOM

April 7, 2020

In simple terms, the VDOM is a virtual, in-memory representation of the browser’s Document Object Model (DOM).

I initially came across this concept while learning React, and it left me with two questions: what’s the point, and how does it work?

Purpose

The VDOM exists to make UI updates predictable and manageable. The real problem it solves is how expensive directly updating the DOM is.

Basically, the browser DOM is very tightly coupled to layout, paint, and compositing. Touching it too often means forcing the browser to constantly recalculate styles and reflow the page.

Early JS frameworks like jQuery or Angular 1 would just mutate the DOM directly and ended up doing far more work than neccessary.

Instead of updating the DOM as your application changes, frameworks like React build a in-memory representation of what the UI should look like. That’s the VDOM.

How it works

As explained above, on each render, React creates an in-memory representation of the UI tree. When state changes, a new VDOM tree is generated.

This tree is then compared to the previous tree using a diffing algorithm to determine what actually changed.

From that comparison, a minimal set of DOM operations required to bring the real DOM in sync is computed.

These updates are then applied in a controlled and batched way. Typically during a single render pass. The browser does less work, and your app avoids a bunch of small layout and paint operations.

TLDR; render to memory first, figure out the smallest possible set of changes, and then only update the real DOM once.