Skip to content

Browser's DOM vs. React's Virtual DOM

Chandrabhatta Sriram edited this page Jul 10, 2020 · 2 revisions

What is DOM?

When we open a website, the browser generally parses the HTML, CSS & JavaScript code using HTML Parser, CSS Parser & JavaScript Engine respectively. With HTML/CSS, the browser generates a DOM (Document Object Model) which is simply an n-ary tree of HTML elements (nodes) of the webpage.

So whenever there's a change in the DOM, the process of rendering the entire webpage is taken place by the browser, again, i.e., the HTML Parser again parses the entire page, and the CSS parser parses the CSS, both are combined and then the DOM is constructed again. All of this happens even for a small change in the DOM using JavaScript (as DOM is the interface between JavaScript and HTML/CSS).

The entire process can be seen below.

DOM Generation in Browsers

This process is painstakingly slow and therefore, Facebook came up with something better when they developed React, which is the Virtual DOM, which instead of re-building the entire DOM tree, just changes the Node (and its children) whose state has been changed.

NOTE: Browser generated DOM will be referred to as Actual DOM or simply DOM.

What is Virtual DOM?

Virtual DOM by React is simply a copy of the Actual DOM tree. What it means is that, React simply copies the entire actual DOM tree as another tree (which is called Virtual DOM) built using JavaScript (and therefore, the Virtual DOM is pure JavaScript Object Nodes in form of an n-ary tree).

Our JSX is internally just JavaScript which looks like it is returning these "HTMLesque" elements, but due to the React's compiler, that "HTMLesque" JSX will be converted down to pure JavaScript internally.

Now, coming back to Virtual DOM, what React does is, after making the copy of the actual DOM as an n-ary tree in JavaScript (which is now the Virtual DOM). Now, in our React project, let's say that there's a change that occurs in a component, and so, because of that, instead of re-rendering the re-building the entire tree, React simply affects the component (and its children) whose state was changed.

React only re-renders the component by actually making another copy of the entire Virtual DOM where it changes the data that actually got affected and wherever that element/component in the Virtual DOM is updating, those same elements/nodes are updated in the actual DOM (without actually re-rendering the entire webpage and building the entire DOM tree again).

Clone this wiki locally