React The Basics - HTML DOM vs Virtual DOM


Example


HTML DOM is Expensive

Each web page is represented internally as a tree of objects. This representation is called Document Object Model. Moreover, it is a language-neutral interface that allows programming languages (such as JavaScript) to access the HTML elements.

In other words

The HTML DOM is a standard for how to get, change, add, or delete HTML elements.

However, those DOM operations are extremely expensive.


Virtual DOM is a Solution

So React's team came up with the idea to abstract the HTML DOM and create its own Virtual DOM in order to compute the minimum number of operations we need to apply on the HTML DOM to replicate current state of our application.

The Virtual DOM saves time from unnecessary DOM modifications.


How Exactly?

At each point of time, React has the application state represented as a Virtual DOM. Whenever application state changes, these are the steps that React performs in order to optimise performance

  1. Generate a new Virtual DOM that represents the new state of our application

  2. Compare the old Virtual DOM (which represents the current HTML DOM) vs the new Virtual DOM

  3. Based on 2. find the minimum number of operations to transform the old Virtual DOM (which represents the current HTML DOM) into the new Virtual DOM

  • to learn more about that - read React's Diff Algorithm
  1. After those operations are found, they are mapped into their equivalent HTML DOM operations
  • remember, the Virtual DOM is only an abstraction of the HTML DOM and there is a isomorphic relation between them
  1. Now the minimum number of operations that have been found and transferred to their equivalent HTML DOM operations are now applied directly onto the application's HTML DOM, which saves time from modifying the HTML DOM unnecessarily.

Note: Operations applied on the Virtual DOM are cheap, because the Virtual DOM is a JavaScript Object.