logo

Virtual DOM in react

Why react used virtual DOM

The Virtual DOM is an in-memory representation of the actual UI structure (the real DOM). Think of it as a blueprint of how your UI should look at any given moment. It's a JavaScript object hierarchy that mirrors the structure of the real DOM elements. The Virtual DOM does not directly replace the real DOM. It acts as an efficient intermediary that helps React determine what changes need to be made to the real DOM.

🚀 Lightweight Representation Performance Optimization and Minimized Updates

Web browsers are complex, and directly manipulating the DOM can be relatively slow. Every change to the real DOM forces the browser to recalculate styles, layouts, and trigger a repaint—even for tiny updates. The Virtual DOM minimizes these expensive operations for better performance. Diffing Algorithm React employs a smart "diffing" algorithm. When changes occur in your React components, this algorithm compares the new Virtual DOM to a snapshot of the previous Virtual DOM. It pinpoints the exact differences between them. After the diffing process, React knows the bare minimum set of changes required to update the real DOM. It applies these changes in a batch, maximizing performance and minimizing unnecessary DOM manipulations

After the diffing process, React knows the bare minimum set of changes required to update the real DOM. It applies these changes in a batch, maximizing performance and minimizing unnecessary DOM manipulations.

Key Benefits

Speed

The Virtual DOM and its diffing algorithm allow React to make only the necessary, targeted updates to the real DOM—improving overall rendering efficiency.

Developer Experience

JSX, used within React components,lets you declare the desired UI structure in a manner closely resembling HTML, streamlining the process of defining how the UI should look.

Abstraction

The Virtual DOM relieves you from dealing with low-level DOM manipulation complexities, letting you focus on your application logic and data.

Example

Consider a component that renders a counter button and display. When the button is clicked:

React updates its state to reflect the new count. A new Virtual DOM is generated based on the updated state. React's diffing algorithm compares the new and old Virtual DOMs. It identifies the only change is in the text content of the element containing the count. React updates just that specific text node in the real DOM, avoiding an entire re-render.

👉 Remember :- The Virtual DOM is one of the core concepts behind React's efficiency and declarative programming model.