A virtual DOM is a lightweight JS object. It is simply a copy of the real DOM. A virtual DOM is a node tree that lists various elements, their attributes, and content as objects and their properties.
The render() function in React is responsible for creating a node tree from the React components. This tree is then updated in response to the mutations resulting in the data model due to various actions made by the user or the system.
Virtual DOM operates in three simple steps:The render() function in React is responsible for creating a node tree from the React components. This tree is then updated in response to the mutations resulting in the data model due to various actions made by the user or the system.
- Step 1 – The entire UI is re-rendered in Virtual DOM representation as soon as there are some underlying data changes.
- Step 2 – Now, the difference between the previous DOM representation and the new one (resulted from underlying data changes) is calculated.
- Step 3 – After the calculations are successfully carried out, the real DOM is updated in line with only the things that actually underwent changes.
Virtual DOM VS Real DOM
- DOM Manipulation – Real DOM supports a very expensive DOM manipulation. Virtual DOM, on the contrary, has an inexpensive DOM manipulation.
- Element Update – Real DOM creates a new DOM when an element updates. Virtual DOM doesn’t do so in such a case. Instead, it updates the JSX.
- Memory Wastage – Real DOM causes a lot of memory wastage while there is no memory wastage for Virtual DOM.
- Update Speed – Real DOM updates slowly. On the other end, the virtual DOM updates faster.
- Updating HTML –