If you are like me and just diving into front-end frameworks like React then you’ve probably been amazed by the speed at which these frameworks take your code and render nodes to your DOM. It honestly feels like a magical power. But in reality, this is just an invisible friend helping you out. So let’s meet our new friend: The Virtual DOM
“But Alex, isn’t the DOM already virtual?”
I mean yes, but that DOM and the Virtual DOM aren’t the same thing.
The Virtual DOM and the other DOM (we’ll call it Real DOM from now on) are best friends, and they help each other out a LOT (like, A LOT).
But before I explain their relationship, let’s talk about Real DOM and how it renders your nodes.
The Real DOM loves to draw whole pictures.
What do I mean by that?
I mean that whenever we give the Real DOM a collection of nodes to render on a webpage it is really happy. Real DOM enjoys taking all of your nodes and beautifully painting them in your browser for everyone to see. If you send Real DOM updated data, Real DOM gets so excited that it paints everything all over again.
Real DOM is a skilled painter no doubt, but it is also a slow painter since it completely repaints Every. Single. Node. regardless of whether or not it needs to be updated.
Enter React and the Virtual DOM
The React development team recognized this drawback of manipulating the DOM, and created a helper named Virtual DOM.
Similar to our Real DOM, Virtual DOM is an abstraction of our HTML code.
Unlike Real DOM, Virtual DOM never renders anything in the browser.
Virtual DOM exists purely as lines of code.
This means Virtual DOM is extremely fast at handling changes you may make to your code. Virtual DOM has the ability to communicate these changes to Real DOM through a process called “reconciliation”.
How does reconciliation work?
Let’s assume we’re working in a React app, and we add some code that would add a new node to our DOM.
Previously, Real DOM would have seen that addition, torn down everything and painted a new picture that includes your new element.
But now that Virtual DOM exists, our new element is first given to Virtual DOM. Because Virtual DOM only exists as code it creates a new painting with your addition extremely fast.
Virtual DOM then communicates with Real DOM by saying,
“Hey, here’s the picture I just drew. Looking at the picture you’ve made I can see some differences. How about you update only these parts of your picture so that it matches my picture?”
Real DOM thinks that’s a great idea and then selectively renders the difference and the children of connected to the difference. By communicating with the Virtual DOM, the Real DOM (and you the developer) saves so much time and processing power!
So next time you’re working on a React project, be on the lookout for this unsung hero in your “index.js” file:
import ReactDOM from 'react-dom';
Because this is your buddy, the Virtual DOM, helping you out by speeding things up.