The main part of Virtual DOM can be written in less than ~50 lines of code. […] When we change something in our Virtual DOM Tree, we get a new Virtual Tree. Algorithm compares these two trees (old and new), finds differences and makes only necessary small changes to real DOM so it reflects virtual.
const a = (
<ul>
<li>item 1</li>
<li>item 2</li>
</ul>
);
const b = (
<ul>
<li>item 1</li>
<li>hello!</li>
</ul>
);
// Set content of #root to a
updateElement(document.getElementById('root'), a);
// Set content of #root to b
updateElement(document.getElementById('root'), b, a);
In the image above you can see what happens in the Virtual DOM when a
is replaced by b
(triggered by updateElement(document.getElementById('root'), b, a);
). Only the childElement that is different is updated in the actual DOM.
How to write your own Virtual DOM: Part 1: The Basics →
How to write your own Virtual DOM: Part 2: Props & Events →