๐๐ก๐๐ญ ๐ข๐ฌ ๐ญ๐ก๐ (๐ซ๐๐๐ฅ) ๐๐๐?
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.
๐๐ก๐ ๐๐ซ๐จ๐๐ฅ๐๐ฆ ๐ฐ๐ข๐ญ๐ก ๐๐๐
Given:
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[1] 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.
2๏ธโฃObservable(fast)๐๏ธ
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.
The virtual DOM is a concept implemented by libraries in JavaScript on top of browser APIs.
๐๐ฉ๐๐๐ญ๐ ๐๐ซ๐จ๐๐๐ฌ๐ฌ ๐ข๐ง ๐๐๐๐๐ญ
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
bit.ly/react2023