Demystifying Virtual DOM in React

debajit13

Debajit Mallick

Posted on February 26, 2024

Demystifying Virtual DOM in React

Introduction

Virtual DOM is one of the most crucial topics for a React Developer. The essence of how React renders on the web lies in virtual DOM. This article will explain how virtual DOM works and its nitty-gritty details.

What is Virtual DOM?

The virtual DOM in React is an in-memory representation of the actual Document Object Model that serves as an efficient intermediary for updating the UI.

How it works?

Here is a step-by-step guide on how the Virtual DOM works in React.

Diagram of How Virtual DOM works

State Change

Whenever we call a state updater function via any action or event that triggers a state change in a React component. It signifies that the UI needs to be updated.

Virtual DOM Update

React doesn't update the actual DOM directly. Instead, what it does is create a new lightweight representation of the UI based on the updated state. This new representation is the virtual DOM. The virtual DOM is essentially a JS object tree that mirrors the structure of the actual DOM.

Diffing

React compares the old virtual DOM with the new virtual DOM. This process is called Diffing. During diffing, React identifies the minimal changes required to transform the old virtual DOM into the new one. This includes additions, deletions, or modifications to specific elements and attributes.

Reconciliation

Based on the differences found in the Diffing process, React determines the most efficient way to update the original DOM. This process is called Reconciliation. Instead of blindly re-rendering the entire DOM, React only updates the specific elements and attributes that have changed. This minimizes unnecessary DOM manipulations.

Real DOM Update

React efficiently updates the real DOM based on the instructions from the Reconciliation step. This involves adding, removing, or modifying elements and their attributes as needed. The real DOM now reflects the updated state and the UI is visually changed accordingly.

Conclusion

The virtual DOM itself is not directly displayed on the screen. It's an internal representation used by React to optimize updates. React's ReactDOM library handles the communication between the virtual DOM and the real DOM. If you like this blog and want to learn more about Frontend Development and Software Engineering, follow me on LinkedIn.

💖 💪 🙅 🚩
debajit13
Debajit Mallick

Posted on February 26, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Demystifying Virtual DOM in React
webdev Demystifying Virtual DOM in React

February 26, 2024