How to understand by Virtual DOM ?
DOM is a Document Object Model which represents the content of XML or HTML document as a tree structure so that the programs can be read, access, and change in the document structure, style, and content.
Let’s see how a document is parsed by a DOM. Consider the following sample HTML code.
The above code creates a tree structure as shown below:
Now we got a basic idea of what DOM is, If you are still unsure about it please learn here.
When you run a code, the web page is divided into different modules. So, virtual DOM compares it with DOM and checks if there is any difference. If it finds a difference then DOM updates only the modified part and the other part remains the same.
As shown in the above image, virtual DOM is different from DOM, now DOM updates the child components which are different and the other remains exactly the same. This increases the performance.
Now let’s see an example of how Virtual DOM works:
Creating a React application:
- Step 1: Create a react application with the following command.
npx create-react-app foldername
- Step 2: Change your directory to the newly created folder with the following command.
Project Structure: It will look like the following:
Implementation: Write down the following code in respective files.
Step to Run Application: Run the application using the following command from the root directory of the project:
Output: Open your browser and right-click on the screen and select Inspect. You can see the following output.
As you can see from the above output, the whole div element is updating along with the time in the DOM. Whereas in virtual DOM only the h4 element is been updating and every other element is remaining the same. So this shows that virtual DOM finds the modified part and updates only that modified part.