sanjiv chavan
sanjiv chavan

Reputation: 21

why there is need to create virtual DOM in React.js rather than directly update all node in browser DOM?

in react js in reander it create virtual DOM compare with browser DOM and update browser DOM. Rather than having virtual DOM why not to update directly in browser DOM.

Upvotes: 2

Views: 186

Answers (2)

Pipe Runner
Pipe Runner

Reputation: 82

The DOM is made up of nodes that are rendered by your browser. As your application receives input from the user, it has to change certain nodes in order to show it's response (Ex- A button turning blue from red when the user clicks on it). Now, DOM is not good at doing anything smart. So, any time anything changes, it will re-render every node from scratch. This is a costly process.

React adds the brains to DOM by telling the DOM which node to render and which node to leave as it was. (Ex- Except the button, everything else in the UI should not change). This is done by storing the state of your DOM in JS in the form of nested objects (Forming a tree like strcuture). Changes to specific parts of this object will help React figure out which part of the DOM tree actually needs to be re-rendered. This is done using the concept of immutability which is very nicely explained in the ReactJS docs. So it basically diffs the new object with the old one and tells the DOM to make changes to specific nodes ONLY, thus improving performance by many folds.

Upvotes: 0

Hnus
Hnus

Reputation: 959

Performance. Reading/writing to DOM is very expensive. It is much faster to calculate changes on JS data structure and then just do minimal amount of changes on real DOM. Except for some special cases you can avoid reading browser DOM alltogether thats why react is so fast.

Check this simple benchmark as you can see reading is not expensive. Writing is also not expensive but reading and writing is crazy expensive. (updateNode function does reading and writing)

enter image description here

Image is taken from this talk which I really recommend.

Upvotes: 1

Related Questions