Table of contents
No headings in the article.
If you work with react, you must have heard about virtual DOM. Let's understand what's virtual DOM and how react works under the hood.
Before moving to virtual DOM, let us first understand what is DOM
- DOM stands for ‘Document Object Model’. In simple terms, it is a structured representation of the HTML elements that are present in a webpage or web app. DOM represents the User Interface of your application, it's represented as a tree data structure where each element is a node.
DOM manipulation/ DOM updation:
If you have worked with javascript before then you have probably modified the DOM before, remember 'document.createElement()' or 'document.body.append()', these functions are used to update or modify the elements of our data object model and this is how we manipulated DOM using vanilla javascript.
Now let's see how things work in React, let's start with basics
What is virtual DOM?
In React for every DOM object, it creates a corresponding virtual DOM object.
Essentially virtual DOM is just a copy of DOM but it lacks the ability to change what's on the screen.
Why was virtual DOM required?
- DOM manipulation is the most important part of the modern and Interactive web, but manipulating DOM is slow.
Why is DOM manipulation slow?
Suppose a web page have 10 components and after clicking a button on the page we have to update only one of the component.
Changing this one component will update the entire DOM, which means 9 components were updated unnecessarily. This Increases the overhead on every manipulation and is not very efficient.
How does virtual DOM solve this problem?
When you render a JSX element, every virtual DOM object gets updated. It's fast because the virtual DOM updates quickly.
After the update, React compares the current virtual DOM with the virtual DOM snapshot taken just before the update.
After comparison, React knows exactly which component have been updated in the DOM.
React then updates the changed component in the real DOM.
Advantage:
Now we don't have to update the entire DOM just to change some components.
This means fewer updates, low overhead and faster DOM manipulations.