Some of our Cronj blog readers from the USA messaged to us and asking to “We need the clear picture of DOM, How it wil going to work?”. In considering their request, we have published this article and in addition to that we have mentioned: “what is browser & Virtual DOM?”
What is DOM?
<html> <head> <title>Cronj Blogs</title> <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /> </head> <body> <a href="https://www.cronj.com">Home</h1> <p>Multinational Web and Mobile Development Company</p> </body> </html>
So, the tree is generated as,
Please go through below picture you will get some better idea.
Now, If you can see the highlighted part is from where our HTML node starts forming a tree. And we consider it as DOM object. If you can see cssStyleDeclaration is a sibling of node/Html and that is why which is not present in the subtree of HTML as a parent.
If Document Object Model is so cool, then why to go with Virtual DOM?
Let’s take an example,
You have asked to decorate the room with 100 balloons. You have decorated the room with 100 balloons.
Now your mentor told you the color of each balloon should be red. so you remove all the balloons and now decorate the room with red balloons.
Mentor comes and asks you now change the change the balloon no 90 with a blue colored balloon. now you remove all balloons and bring 99 red balloons and 1 blue balloon and paint accordingly.
Mentor comes and asks please change balloon no 80 to green. You remove all the balloons. Go market bring 98 red, 1 blue, 1 green. And decorate the room accordingly.
WOW, will you work this way? No. right? but your Document Object Model does. So, how to make DOM intelligent?
Now, VIRTUAL DOM comes to rescue us.
What is the Virtual DOM?
It is a React’s Object that represent the Browsers DOM, Which is intelligent to make changes in the DOM with the help of Diff Algorithm. Few Blog says, it is so fast that it can produce 20000 nodes per second.
Now, How does Virtual DOM work?
1. Whenever a Document Object Model is rendered into browser React generate a copy of that object as a Virtual DOM.
2. When the user interacts and we want to change the Document Object Model, first we generate another copy of it.
3. We compare virtual DOM vs another copy of it, if there are changes then only we will render the Browser Document Object Model, otherwise, we won’t.
4. Now if we got some changes between them, react is intelligent to find which node has changed. React tells browser Document Object Model “Hey! this node subtree needs to change, everything else remains as it is”.
5. Browser thanks to react saying, I am very good at painting the things but you told me where to paints and that’s why we are doing fast.
RegularDocument Object Model takes O(n^3) for generating UpdatedDocument Object Model where Virtual DOM is O(n) to almost all the practical user cases.
Looking for ReactJS Development Company? Hire our dedicated developers!