Introduction
In modern web development, performance and efficiency are critical part when creating user interface. Virtual DOM is one of the key innovations which make framework like React fast and efficient. But what is exactly virtual DOM?. How does it works. Let's understand in detail in this blog.
What is Virtual DOM?
The DOM (Document object model) represent the structure of the webpage as tree elements. when any changes made in the UI the browser update the DOM, which can be slow and inefficient specially If the application is large.
To solve this problem Virtual DOM was introduced which is abstract representation of DOM. when any changes made in the UI instead of modifying directly real DOM. changes first apply to Virtual DOM only necessary changes are made to real DOM which improve the performance.
How does Virtual DOM works?
The Virtual DOM follows three-steps process to efficiently update the UI.
1. Rendering the Virtual DOM
- When a React component renders, a Virtual DOM created.
- This is light weight copy of actual DOM, but this exist only in memory.
2. Comparing the Changes
- when the application state changes. a new Virtual dom is generated.
- React compares the changes with previous one using a process called as Reconciliation.
- It check what part of UI is changed.
3. Updating the real DOM
- React applies only necessary update to real DOM instead of updating the entire UI.
- This reduce the performance issue and make the rendering faster.
Why virtual DOM is faster?
- Instead of making multiple update to DOM. It update it in bulk. React group all change and update in the single batch.
- React calculate the changes and applies only when need instead of repainting the entire UI.
Example: Virtual DOM in action.
function Counter() {
const [count, setCount] = React.useState(0);
return (
Counter: {count}
setCount(count + 1)}>Increment
);
}
- When a button click setCount update the state.
- A new virtual DOM is created with the update count value
- React compares it with previous virtual DOM and find that only h1 tag has changed.
- Instead of re-rendering the whole page. React update the only h1 tag.
This was all about Virtual DOM. What are your thoughts on this. Let me know in the comment section