TIL How a virtual dom works
POSTED ON:
TAGS: virtualdom dom react vue
Virtual Dom Vs Actual DOM #
When you build HTML elements in Javascript, it looks like this:
const listItems = ['alpha', 'bravo', 'charlie', 'delta', 'echo'];
const container = document.getElementById('container');
const ul = document.createElement('ul');
for (i = 0; i <= listItems.length - 1; i++) {
const li = document.createElement('li'); // create li element.
li.innerHTML = listItems[i]; // assigning text to li using array value.
ul.appendChild(li); // append li to ul.
}
container.appendChild(ul); // add ul to the container.
Essentially, HTML are just data nodes.
In other words, JS creates HTML in a AST tree (I think, I forgot where I read that).
This is how Vue works under the hood.
- Your jsx/vue compiles into JS code.
- It returns that JS code, creating a virtual dom behind the scene.
- While generating a actual dom.
So the virtual dom is built in a AST tree, and it's just a super small file.
So this is how it moves so fast.
Then, the Virtual dom compares diffs from old virtual dom, and then reapplies it. We apply the minimal amount of changes.
This is why people say, "Touching the dom is slower."
ACTUAL DOM
document.createELement('div')
VIRTUAL DOM
vm.$createElement('div')
Related TILs
Tagged: virtualdom