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:
Compare it to a process being an instance of a program. You can have multiple processes of the same one program, just like you can have multiple DOMs of the same HTML (e.g. the same page loaded on many tabs).
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:
<li>Make grocery list <button>Delete</button> </li>
<li>Water plants <button>Delete</button> </li>
<li>Wash sheets<button>Delete</button> </li>
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:
Think of manipulating the virtual DOM as editing a blueprint, as opposed to moving rooms in an actual house.
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!