Concept Of Virtual DOM in ReactJS

I’ll try to convey the concept of “Virtual DOM in ReactJS” in ReactJS. First, we need to learn about the DOM and then we’ll move to forward. So, let’s start!

What is DOM?

DOM stands for Document Object Model.  In the browser, HTML turns into the tree data structure according to the W3C standards. This tree structure is known as the DOM.  All HTML elements save in DOM. DOM is constructed by the nodes, like the first node in DOM is the “document”. Javascript, JQuery or other scripting language are used to manage the DOM i.e create, update and delete the DOM nodes. In short, the browser takes HTML as input and then save the HTML elements in the form of DOM. Each DOM object has own style, attributes, and events.

DOM and Javascript

Javascript is used to perform the DOM manipulation. So, the first thing is how to access the DOM element through the javascript and we should know the element name. We can access the HTML element by Tag, Id or class name. If we put the console.log(document.all) and press enter key in browser console then we can see all elements in the hierarchy form in the browser console. Let’s try to change the website title; document.title = “My Title” then press enter key. Now we can see page title has been changed. The DOM tree builds every time when any manipulation occurs in DOM.

Virtual DOM in ReactJS

Manipulation in DOM slow down the webpage performance because of browser recalculates the element positions in the document and re-rendering is occur. React uses the virtual DOM that’s why ReactJS works fast. Actually, virtual DOM is the javascript object and copy of actual HTML DOM. Whenever react component’s state change or shouldComponentUpdate method call, ReactJS compares in virtual DOM and just update the desired node in the actual DOM.

1 -> Build in-memory virtual DOM (copy of actual DOM) 2 -> Find the differences 3 -> updates the actual DOM (browser’s DOM).

Thanks for reading my blog. Read my other blogs.