December 12, 2020
In the simplest sense, the virtual DOM is a copy of the real DOM. There are a number of libraries that offer a virtual DOM but I'll be using React's virtual DOM to explain what it is and to make comparisons between it and the real one.
What is the DOM?
Let's start by going over what the real DOM is. The DOM (document object model) is a programming interface for XML and HTML documents.
In the DOM, HTML/XML documents are represented as nodes in a node tree. In a node tree there is a single parent stem that branches out into several child branches. Each child can have multiple leaves.
The easiest way to picture this if this is your first time reading about this concept is to think of a family tree. Obviously there would never be a single parent stem as, at least as far as I know, it takes two to produce offspring ;P. However, if you were to focus on just one of your ancestors and the family that followed, it becomes really easy to grasp what a node tree is.
Only, to better visualize a DOM node tree, we need to turn this family tree on its side.
Now let's look at an HTML document converted into a node tree. Below we see a pretty basic HTML document.
And here is the same document node tree form.
When is the DOM Not an Exact Representation of the HTML Source?
There are two instances where the DOM may not reflect the HTML document exactly. The first is if the HTML is invalid. In the following example, the required head and body tags are missing but we can see this has been corrected in the DOM tree.
What is a Virtual DOM and Why Do We Need It?
The virtual DOM is a representation of the real DOM. It is kept in memory and synced with the real DOM after a state change has occurred, through the process of reconciliation. During this process, React will respond to a component's state change by comparing the virtual DOM, which holds the updated state, to the real DOM.
When an entry is made to the following input field
React creates a new tree.
The new state in the virtual DOM is compared to the old version of the DOM, figures out the difference between the two versions, and makes an update only to the part that is different.
Keep in mind, when building any React application that unnecessary re-renders are expensive and reconciliation should be avoided unless needed. For more information on this, see the section title 'Avoid Reconciliation' in React's Optimizing Performance docs.