Virtual DOM in React

Learn via video courses

Overview

Document Object Model is referred to as DOM. It is a structured representation of the HTML elements that are found in a webpage or online application. The complete UI of your program is represented by the DOM.

One of the key React ideas is the react virtual DOM. If you have built React code in the last few years, you have probably heard of it.

What is Virtual DOM in React?

Let's review the actual browser DOM to better grasp the react virtual DOM and discover why React uses it.

In most cases, when a user requests a web page, the browser gets an HTML version of that page from the server. The user can then view the requested page in the client when the browser creates a logical tree-like structure from the HTML. The Document Object Model, also termed the DOM, is the name of this tree-like structure. The web document, in this case, an HTML document, is structurally represented by nodes and objects.

React utilizes Virtual DOM, which functions as a lightweight replica of the real DOM (a virtual representation of the DOM). Therefore, there is one object in React Virtual DOM for every object that is present in the real DOM. Although it is identical, it is unable to alter the document's design in any way. DOM manipulation takes time, but react virtual DOM manipulation happens quickly because no images are being drawn on the screen. As a result, the virtual DOM rather than the real DOM is updated first whenever the state of our application changes. You may still be thinking, "Aren't we repeating the same mistake and doing twice as much work? How is this any quicker?"

The react virtual DOM is a representation of a DOM object. Every DOM element in React JS has a matching Virtual DOM Object. The virtual DOM unquestionably has the same attributes as the DOM object, but unlike the DOM object, which allows us to directly alter what is on the screen, we are unable to do that with the virtual DOM.

what-is-virtual-dom-in-react

Working on Virtual DOM

React compares the react virtual DOM with a snapshot of the initial state before every update made to the virtual DOM. React js uses this comparison to determine which portion of your react component needs to be updated automatically. It's interesting to note that React accomplishes this utilizing what we refer to as the diffing algorithm, and the use of this technique is referred to as diffing. React then updates the components that require updating with the updated nodes after comparing the results. Let's examine some sample code to see how it appears.

Initial DOM State:

Update DOM State:

According to the second section of code, the DOM only modifies its content when it receives an update. Since this update happens so quickly, we frequently are unaware of it. It just identifies the component that needs to be updated and does the change for us.

Let's visualize the react virtual DOM to better illustrate this:

update-dom-state

The original render is seen on the left-hand image. React builds a new tree with the modified node as the time changes, as can be seen on the right. Keep in mind that the virtual DOM is merely an object that represents the UI; nothing is displayed on the screen.

React builds a new virtual DOM tree and then uses a diffing mechanism to compare it to the previous snapshot to determine what modifications are required. Reconciliation is the name given to this procedure. React employs a renderer library like ReactDOM after the reconciliation process, which uses the updated app information to update the rendered app. This module guarantees that the changed node or nodes are the only ones sent to and painted by the actual DOM:

update-dom-state-2

Only the node whose data changes gets repainted in the actual DOM, as can be seen in the image above. The GIF below demonstrates this further:

update-dom-state-3

As we can also observe, when a state change occurs in the UI, the input value is not lost.

In conclusion, React uses a virtual DOM tree on each render to check that the modified node content matches the actual DOM and to determine which nodes should have their content updated.

Reconciliation in React

React treats every element, whether functional or class, as a separate component. A state may be present in a component. React refreshes its Virtual DOM tree whenever we make a change to our JSX file or, to put it another way, whenever the state of any component changes. Although it would appear to be inefficient, updating the react virtual DOM doesn't need much time; therefore, the cost is not substantial. At any given time, React keeps two Virtual DOMs, one of which is the updated Virtual DOM and the other of which is simply the pre-update version of the updated Virtual DOM.

Now it analyses the react virtual DOM before and after the update to determine exactly what has changed, such as which components, are in the DOM. "Diffing" is the process of contrasting the most recent Virtual DOM tree with the oldest. React updates only those objects on the real DOM after it determines precisely what has changed. Updates to the real DOM are made using batch updates in React. It simply means that batches of changes to the real DOM are transmitted rather than a single update for every time a component's state changes. React accomplishes this most effectively by guaranteeing that the Real DOM receives batch changes to re-render the UI. As we've seen, re-rendering the user interface is the most expensive component of the process. Reconciliation refers to the full process of converting changes to the actual DOM.

This dramatically boosts performance, which is the key factor in why developers from all over the world adore React and its Virtual DOM.

Reconciliation, as mentioned above, is the process of synchronizing the VDOM with the actual DOM. React builds a tree starting at the root node for this to occur. The true DOM, which has four nodes, is represented as a tree in the diagram below.

Real DOM

real-dom

React compares the root components in the react virtual DOM and actual DOM because the app's state changes using its diffing method (quite similar to how Git compares changes in files). It disassembles the affected nodes and remounts them whenever it comes across root elements that have changed. The nodes that get remounted in this example are those that are highlighted in green in the tree representation below.

Virtual DOM

the-virtual-dom

DOM in React

The complete UI of your program is represented by the DOM. A tree data structure is used to represent the DOM. Each UI element found in the web content is represented by a node in this tree. It is particularly helpful since it enables web developers to edit information using JavaScript. Additionally, the fact that the code is organized into targets makes it much easier to deal with.

In most cases, when a user requests a web page, the browser gets an HTML version of that page from the server. The user can then view the requested page in the client when the browser creates a logical tree-like structure from the HTML. The Document Object Model, also termed the DOM, is the name of this tree-like structure. The web document, in this case, an HTML document, is structurally represented by nodes and objects.

The DOM acts as an interface for the online document, allowing JavaScript and other scripting languages to access, interact with, and alter the content of the document programmatically. Developers can add or remove elements, change how they look, and execute user actions on the web elements, for example, using the DOM APIs.

Updating the DOM

If you are familiar with JavaScript, you may have seen people edit the contents of the DOM using the "getElementById()" or "getElementByClass()" methods. The DOM is updated each time the state of your application changes so that it is reflected in the user interface. Though carrying out such actions is not problematic and it functions as intended, imagine that our DOM has several nodes and that each of these web elements has a unique set of styling and attributes.

Since DOM is itself represented as a tree, updating the tree, in this case, is not a time-consuming process; in fact, we have several algorithms on trees to make the changes quickly. The modified element and its children must be rendered anew to update the UI of our page whenever the DOM is updated, which is proving to be expensive. Similarly, the DOM must be updated and the UI components must be rendered again whenever a component is modified.

Example

These things occur when writing the aforementioned code to the console or a JavaScript file:

  • To locate the node with this id, the browser parses the HTML.
  • It eliminates the specific element's child element.
  • Adds the "updated value" to the element (DOM).
  • Updates the parent and child nodes' CSS values.
  • Refresh the design.
  • Finally, go around the tree and draw it on the browser's screen.

As a result, we are aware that altering the DOM entails much more than simply modifying the content. Additionally, updating the CSS and altering the layouts need complicated algorithms, which do have an impact on performance. React uses something called virtual DOM to handle this in a different way than other frameworks.

How to Make Things Faster with Virtual DOM in React?

A react virtual DOM is formed whenever something new is introduced to the application, and it is visualized as a tree. A node in this tree represents each component of the application. Therefore, a new Virtual DOM tree is constructed whenever the state of any element changes. The former Virtual DOM tree is then compared to the new Virtual DOM tree, and any differences are noted. The optimal technique to make these changes to the real DOM is then determined. Only the changed items will now be displayed once more on the page.

Virtual DOM is incredibly quick because there is no direct access to or modification of the DOM elements. Additionally, react only examines the DOM elements that require updating before performing the update for those specific elements rather than re-rendering all elements, which reduces throughput and slows component updates.

Some Pros and Cons Regarding Virtual DOM are Given Below:

The virtual DOM offers incredible performance. Beyond that, the virtual DOM has the following benefits:

  • Increased performance and speed Lightweight

  • It is easy to understand.

  • The amazing diffing method that applies to more than only React

  • Since everything that has a benefit also has a drawback, let's look at the negative aspects of virtual DOM:

    Problems with higher memory use because the diffing algorithms must continually compare the pieces to determine which ones require updating or changing.

  • It is difficult to incorporate into a lot of different frameworks.

  • It cannot be utilized or targeted toward template engines.

Because of the improvement in performance and speed, it provides, virtual DOM is always preferred despite the drawbacks listed above.

How Virtual DOM Aids React?

Every virtual DOM object is modified when a JSX element is rendered. This sounds very wasteful, but because the virtual DOM can update so quickly, the cost is negligible.

React compares the virtual DOM with a virtual DOM snapshot that was taken just before the update after the virtual DOM has been updated. React determines precisely which virtual DOM objects have changed by comparing the updated virtual DOM to a previous iteration. "Diffing" is the name of this procedure.

React updates just those objects on the real DOM after determining which virtual DOM objects have changed. In our previous example, React would be wise enough to rebuild the one item on your list that was checked off while leaving the rest of your list alone.

This does change things! React can only update the DOM's essential elements. This innovation is largely responsible for React's performance reputation.

Here is an overview of what takes place when you attempt to update the DOM with React:

  • The virtual DOM is updated in its entirety.
  • The virtual DOM is contrasted with how it appeared before your modification. Determined by React which objects have changed.
  • The only objects that are updated on the real DOM are those that have been altered.
  • The screen changes when the real DOM changes.

How is Virtual DOM Different from Shadow DOM?

Before we conclude, let's address a frequently asked query. Does the virtual DOM correspond to the shadow DOM? Their behavior is distinct, to put it succinctly.

A tool for implementing web components is the shadow DOM. Consider the HTML input element range, for example:

That gives us this result:

how-is-virtual-dom-different-from-shadow-dom

When we use the developer tools in the browser to investigate the element, all we will see is a straightforward input element. The additional components and styles that make up the input slider are, however, encapsulated and concealed internally by browsers.

We may enable the "Show user agent shadow DOM" option from "Settings" in Chrome DevTools to observe the shadow DOM as follows:

how-is-virtual-dom-different-from-shadow-dom-2

In the image above, the structured tree of elements from the #shadow-root inside the input element is called the shadow DOM tree. It provides a way to isolate components, including styles, from the actual DOM.

That way, we are sure that a widget or component’s style - like the above input range - is preserved no matter where they are rendered. In other words, their behavior or appearance is never affected by other elements’ styles from the actual DOM.

Examples for Understanding

We must comprehend the two main stages involved in rendering and reconciliation to comprehend the virtual DOM technique.

React builds a virtual DOM tree that serves as the representation of the application user interface when it is rendered and stores it in memory. React will automatically generate a new virtual DOM tree for the update on the following update or when the data that renders the app changes.

How to Mount an HTML Element to Virtual DOM?

We must first generate our components and then render them to the application's root directory to mount HTML elements to the react virtual DOM. To create components, React JS uses what is known as the JSX syntax. Therefore, we will develop our first component using JSX, a blend of JavaScript and XML, and then render it to the virtual DOM.

  1. Let's start by using the "npx command" to develop a straightforward react app. So, to scaffold a react app, type the following command into your terminal: "npx create-react-app virtual-dom-demo".

  2. After React has been installed, launch the app in your preferred text editor and make a new file called Sample.jsx.

  3. Enter the below code in the Sample.jsx file:

    Export default sample:

    export-default-sample

  4. We've finished building our initial part! What's the best way to mount it to the virtual DOM? The only thing you need to do is open your App.js file, import it, and then render it as seen in the picture below.

  5. Hurray! Your element has been successfully rendered to the virtual DOM, and any modifications

    export-default-sample-2

Fuel Your Full-Stack Passion! Enroll in Our Full Stack Web Developer Course Taught by Industry Experts and Get Certified!

FAQs

Q: Why updating Real DOM is slow?

A: Complex algorithms are used to recalculate CSS and alter layouts, which has an impact on performance. Therefore, updating a real DOM entails several other procedures in addition to simply updating the DOM.

Q: How does Virtual DOM solve the problem of slow update of real DOM?

A: Updating virtual DOM in ReactJS is faster because ReactJS uses

  • Efficient diff algorithm
  • Batched update operations
  • Efficient update of subtree only
  • Uses observable instead of dirty checking to detect the change

Q: What is react fiber?

A: The new reconciliation engine in React 16 is called Fiber. Its major objective is to make it possible to incrementally render the virtual DOM.

Q: Is the Shadow DOM the same as the Virtual DOM?

A: No, they're unique. A browser feature called the Shadow DOM was created largely for CSS and variable scoping in web components. On top of browser APIs, JavaScript libraries implement the idea of the react virtual DOM.

Conclusion

To help us write more predictable code, the virtual DOM offers a method that abstracts manual DOM manipulations away from the developer. To do this, it compares two render trees to ascertain precisely what has changed and updates the actual DOM just as necessary.

The takeaway points from this article are:

  • The react virtual DOM is a representation of a DOM object. Every DOM element in React JS has a matching Virtual DOM Object.
  • React compares the react virtual DOM with a snapshot of the initial state before every update made to the virtual DOM. React.js uses this comparison to determine which portion of your react component needs to be updated automatically.
  • Reconciliation is the process of synchronizing the VDOM with the actual DOM. React builds a tree starting at the root node for this to occur. It refers to the full process of converting changes to the actual DOM.
  • The complete UI of your program is represented by the DOM. The DOM acts as an interface for the online document, allowing scripting languages to access and alter the content of the document.
  • Virtual DOM is incredibly quick because there is no direct access to or modification of the DOM elements. It offers incredible performance because it increases the performance speed and it is lightweight.
  • A tool for implementing web components is the shadow DOM and The react virtual DOM is a representation of a DOM object.
  • An example of how we mount an HTML element to virtual DOM.
  • And last, some FAQs regarding virtual DOM in react.