𝐖𝐡𝐚𝐭 𝐢𝐬 𝐭𝐡𝐞 (𝐫𝐞𝐚𝐥) 𝐃𝐎𝐌?
The DOM is an abstraction of a page’s HTML structure.
It takes HTML elements and wraps them in an object with a tree structure.
This provides an API that allows us to traverse nodes (HTML elements) and manipulate them in several ways.
𝐓𝐡𝐞 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐰𝐢𝐭𝐡 𝐃𝐎𝐌
let fruits = ['Apple', 'Orange', 'Banana'];
Let's say we want to update the 'Orange' element with a 'Lemon' element.
Then we need to create a new array:
let fruits = ['Apple', 'Lemon', 'Banana'];
Efficiently, we can just traverse to the fruits and update only this element.
Now it’s common to have a thousand node in a single SPA.😱
So repainting the whole page for each change is very very expensive.🤑
Ideally, we’d like to only re-render items that receive updates, leaving the rest of the items as is.
𝐓𝐡𝐞 𝐌𝐞𝐭𝐡𝐨𝐝𝐬 𝐨𝐟 𝐮𝐩𝐝𝐚𝐭𝐞
1️⃣Dirty Checking (slow)🐌
In AngularJS 1.x, data changes were checked by recursively traversing every node at fixed intervals, which was inefficient as it required examining all nodes even if their data was up-to-date.
Components are responsible for listening when an update takes place.
Since the data is saved on the state, components can simply listen to events on the state and if there is an update, it can rerender to the UI.
React uses it.
𝐕𝐢𝐫𝐭𝐮𝐚𝐥 𝐃𝐎𝐌 👻
The Virtual DOM is a lightweight 🪶 abstraction of the DOM.
You can think of it as a copy of the DOM, that can be updated 🔄️ without affecting the actual DOM.
It has all the same properties as the real DOM object but doesn’t have the ability to write ✍️ to the screen like the real DOM.
The virtual DOM gains its speed and efficiency from the fact that it’s lightweight.
A new virtual DOM is created after every rerender.
𝐔𝐧𝐝𝐞𝐫 𝐭𝐡𝐞 𝐡𝐨𝐨𝐝 ⚙️
Reconciliation is a process to compare and keep in sync the two files (Real and Virtual DOM).
Diffing algorithm is a technique of reconciliation 🤝 which is used by React.
Is Shadow DOM the same as the Virtual DOM?
No, they are different.
The Shadow DOM is a browser technology designed primarily for scoping variables and CSS 🎨 in web components.
𝐔𝐩𝐝𝐚𝐭𝐞 𝐏𝐫𝐨𝐜𝐞𝐬𝐬 𝐢𝐧 𝐑𝐞𝐚𝐜𝐭
On the first load, ReactDOM.render() will create the Virtual DOM tree and real DOM tree.
As React works on Observable patterns, when any event(like the key press, left click, API response, etc.) occurred, Virtual DOM tree nodes are notified 🚨 for props change.
If the properties used in that node are updated, the node is updated else left as it is.
React compares Virtual DOM with real DOM and updates real DOM.
This process is called Reconciliation 🤝.
React uses Diffing algorithm technique of Reconciliation.
Updated real DOM is repainted 🖌️ on the browser.
#react #virtualDOM #programming