What actually is Virtual DOM?

Hello Reader, recently I encountered a but obvious question from an interviewer, "What exactly is Virtual DOM?". For the next five minutes, I was explaining how it works and why is it efficient but this didn't answer the question asked. If you are already working with ReactJS or are new to it then you surely would have encountered the same question a gazillion times but unfortunately, not all of us have a clear understanding of what a virtual dom is.

I then read a couple of articles, ReactJS documentation and watched a few videos, and came up with an understanding of Virtual DOM. Hence, I will try to give a proper explanation of what is a Virtual DOM and how does it help in the faster rendering of components.

Table of contents

What is DOM?

If you are coming to learn about Virtual DOM, you definitely would be knowing DOM, but to give a small gist we will go through it. It is perfectly fine to skip this part.

The Document Object Model(DOM) is a structured model representation of HTML and XML documents. In simple words, the elements present on a webpage can be viewed in form of a tree, where the nodes are parent HTML tags and the branches include their respective children tags.

Consider this example of a form visible on a webpage:

The DOM of this form will look like this:

Yes, the DOM is actually similar to the HTML one must have written for the form. Then how is DOM different from any HTML document? HTML is what the server sends in response to a request whereas DOM is built by the browser on top of the HTML received. The key difference still being that DOM is a model of a document that has various APIs through which we can manipulate the HTML over time.

What is Virtual DOM?

Now, since we have an understanding of DOM, so let's dive deep into the world of Virtual DOM.

Here we will try to explore Virtual DOM using React components because what's better than finding an answer in the question itself.

We will now create a simple React functional Component and further instead of rendering it, we will just try to log it in the console:

const DummyComponent = ({title}) =>{
    return(
           <div className="container">
                  <h1>{title}</h1>
                  <h3>This is a dummy component</h3>
           </div>
    )
}

console.log(DummyComponent("Calling the dummy component"))

Now check what has been logged in the console. Kaa-Boom šŸ’„, an object has been logged that has all the details of the component you just created. Have a look at the object and its keys, the props key contains the children's elements along with the other props passed to the component. This is what a Virtual DOM looks like.

By definition, a virtual DOM object is a representation of a DOM object, like a lightweight copy. So, now we can understand this definition more clearly. Virtual DOM is an object representation of the actual DOM rendered, it has all the DOM properties but is only present in the memory and cannot impact what gets rendered on the webpage.

Manipulating Virtual DOM is faster as compared to manipulating the actual DOM, the reason being that the Virtual DOM is only present in memory and can easily be created or deleted.

Note: To get more clarity on the object logged, you can refer to this video.

How do rendering components work with Virtual DOM?

Now that we have a basic understanding of DOM and Virtual DOM, we will have a look at the differences between the process of rendering elements using DOM and Virtual DOM.

In simple DOM manipulation, let's say we want to handle the click event for any button <button id="btn">Click me!</button>, then we first need to have access to this element using the getElementById('btn'), this method will traverse through the complete DOM and will find the element with the specific ID and then will perform the DOM manipulation using other traversing cycle. This process is simple if we have to deal with a small number of elements but let's say we have an application to view stock market trends, prices of various stocks, and related news, now in this application, we have thousands of components, the data inside them may change a couple of times within a second, and so handling this using simple DOM manipulation technique might be a tedious and time taking task. To overcome this drawback, React uses Virtual DOM for its DOM manipulation process.

In React, every component keeps an eye on its state and other parameters on which rendering of that component depends. Let's say that in our component there is a state change and re-rendering of the component is required, here the Virtual DOM comes into the picture, the whole process involved in rendering is as follows:

  1. At the initial step, React will take a snapshot of the actual DOM currently present (DOM present before the re-render happens) and will store it in the memory, for now, we can call it Real Virtual DOM.
  2. Now, React will create a new Virtual DOM from scratch which has all the old components plus the new change, this means React doesn't know the previous DOM. It will consider all its components as new. The new Virtual DOM created is kept separate from the old Virtual DOM and doesn't do any change to the actual DOM.
  3. In the third step, React will compare both the Virtual DOMs and will find out the new change that has to be implemented and its position. This comparison is done using the "Diffing Algorithm" and the process is called "diffing". There is a whole lot that does behind the scenes while performing diffing, you can learn more about it here.
  4. Once the change has been detected, React will now remove the old component from the actual DOM and paint this new component onto the actual DOM. This process goes like, firstly the component that has to be removed receives componentWillUnmount() lifecycle method which removes it, after this the new component that has to be pained receives componentWillMount() and componentDidMount() that brings the new component to the frontend. This process of syncing Virtual DOM to the real DOM is acknowledged as Reconciliation.

This completes the workflow of Virtual DOM. This might seem a time taking process because it involves few crucial steps, but remember most of these steps are being executed in Virtual DOM which is basically objects stored in the memory until the last step where we truly need to change the actual DOM.

So, this sums up the Virtual DOM and how it helps React in rendering components. If there is something that I missed or you would like to add then please provide your valuable feedback. Also, if there is anything you would like me to write about in the future then please let me know.

P.S. Trying my hands at writing for the first time.

21