The Virtual DOM Explained

Devante Lowery
3 min readMay 3, 2021

A quick rundown..

Photo by Pankaj Patel on Unsplash

What is React?

Before getting into the virtual DOM we must first know about React. Unless you’ve been living under a rock, React is one of the most popular frameworks in the web development world. React was created originally at Facebook and has enjoyed solid growth since its inception.

If you are using Javascript you’ve likely heard of the DOM (Document Object Model) before. Today we’ll talk about the differences between the real DOM and the Virtual DOM and how things work.

Real DOM

In layman’s terms the DOM represents the UI of your application. It’s a programming interface for HTML and XML documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects. That way, programming languages can connect to the page.

The problem is that in modern complex applications it can be slowed down tremendously. Imagine constantly re-rendering every element on the page every time something changes. To address this problem, the people at React popularized something called the virtual DOM.

The Virtual DOM

In React, for every DOM object, there is a corresponding virtual DOM object. The virtual DOM is a programming concept where a virtual representation of a UI is kept in memory and synced with the “real” DOM.

A virtual DOM object has the same properties as a real DOM object, but it lacks the real thing’s power to directly change what’s on the screen. Each React component has a render function, and when we call that render function a node tree is created from that particular React component. This tree is then compared or “diffed” with the previous virtual DOM tree.

When the state of a component changes, React updates the virtual DOM tree. Once the virtual DOM has been updated, React then compares the current version of the virtual DOM with the previous version of the virtual DOM. This process is called “diffing”.

Shows the diffing process.

React uses a batch update system to update the real DOM leading to increased performance. So basically updates to the real DOM are sent in small changes instead of sending updates for every single change in state and since

I like to think of the manipulating the virtual DOM as editing a word in an essay rather than deleting it and completely starting over.

A Quick Rundown

  1. The entire virtual DOM gets updated.
  2. The virtual DOM compares what the previous version looked like.
  3. React decides what has changed.
  4. The real DOM is updated with ONLY the changes from the virtual DOM.
  5. Changes on the real DOM cause the screen to change.

--

--