React Concepts 101: The Virtual DOM

About a month ago, I had a mock technical interview and the interviewer asked me what the Virtual DOM was. Although I was familiar with the concept, I could not explain it in words. So now, I am going to redeem myself and explain it here so I will never have that problem again.

What is the DOM?

The DOM stands for Document Object Model. The DOM represents the code-based version of a web page. When you type in a URL in your web browser of choice, the server sends the HTML code of the web page to your browser, which it then renders onto your screen. This quote from React Kung Fu really helped me:

When you are using Vanilla JavaScript in an application, you are manipulating the DOM with event listeners, rather than completely modifying the base HTML code provided by the server.

The Problem with DOM Manipulation

While Vanilla JS and DOM Manipulation work in practice, it quickly becomes incredibly inefficient and difficult to manage. Let’s say you’ve got a basic to do list with a delete button on every item:

<ul>
<li>Make grocery list <button>Delete</button> </li>
<li>Water plants <button>Delete</button> </li>
<li>Wash sheets<button>Delete</button> </li>
</ul>

With plain old DOM manipulation, if you pressed the Delete button on “Water plants,” the JavaScript would edit every single list element, rather than just finding the one that needs to be deleted and updating it accordingly. This can slow things down a lot in the long run. And the bigger the application, the more performance speed and efficiency becomes the key to success.

The Virtual DOM

To solve this issue with DOM manipulation, the creators of React popularized something we call the Virtual DOM. Essentially, it is a copy of the DOM that allows React to do what it needs to do without the slow DOM manipulation issue discussed above. I like the way Codecademy describes it:

With the virtual DOM, instead of updating every single element on a page when it is re-rendered, the virtual DOM compares the current page with a “snapshot” of the page before it was manipulated, and only updates the elements that have changed to the real DOM. In the example above with the to do list, using the virtual DOM we would be able to find just the “Water plants” element that needs to be deleted and taking it out. So much better!

This is why React has such a high performance, and in my opinion why so many large companies prefer to use it. You can also read up more on the Virtual DOM in the React documentation here. Hope this helps, and happy coding!

Blaire is a musical theatre performer who also moonlights as a full-stack software engineer. https://www.linkedin.com/in/blaire-baker