React Virtual DOM Representation

Hello again! This is the second part of the Inside React series. If you didn’t catch the first post, now’s the perfect time to give it a read.

In React, knowing about the Virtual DOM is super important. It’s like the engine that powers React’s speed and efficiency. In this blog, we’ll take a deep dive into what the Virtual DOM is, how it helps make React fast, and where you can use it in real projects. We’ll keep things easy to understand and use lots of examples to show you exactly how it works.

The Virtual DOM

The virtual DOM, similar to the DOM, represents an HTML document as a JavaScript object. While the real DOM is made up of Node objects, the virtual DOM consists of plain JavaScript objects acting as descriptions. This lightweight copy enables developers to create more efficient and performant user interfaces.

In React, when we trigger a UI change with methods like setState, the virtual DOM is updated first, followed by updating the real DOM to match. This process is called reconciliation (More about this in next blog).

Updating the virtual DOM is faster because it doesn’t directly affect the page layout. It’s a JavaScript object that can be manipulated quickly and efficiently. React uses a diffing algorithm to identify differences between old and new virtual DOM versions, then applies minimal changes to the real DOM in a batched and optimized manner to minimize performance impact.

//Sample Virtual DOM
{
type: ‘div’,
props: {
className: ‘container’,
children: [
{
type: ‘h1’,
props: {
children: ‘Hello, world!’
},
// Each component can have additional properties for reconciliation
// and tracking purposes
key: ‘header-123’, // Unique identifier for reconciliation
ref: null, // Reference to the rendered DOM node
_owner: null, // Reference to the owning component
_store: {} // Internal data store for React
}
] },
key: null, // Key for reconciliation of the root element
ref: null,
_owner: null,
_store: {}
}

What’s the problem with Real DOM?

Performance!

One significant challenge posed by the real DOM is its performance. When any change occurs, like adding or removing an element, or altering text or attributes, the browser must recalculate the layout and repaint affected areas of the page. This process can be sluggish and demanding on resources, particularly for extensive or intricate web pages. You can read about the whole browser rendering process here.

Consider a scenario where we have a list of 1000 items displayed on a web page. If we want to add a new item to the list, updating the real DOM requires inserting the new item into the appropriate position in the DOM tree. This operation can be costly, as it involves reflowing and repainting the affected portions of the page.

<body>
<ul id=”itemList”>
<li>Item 1</li>
<li>Item 2</li>
<!– … 998 more items … –>
<li>Item 1000</li>
</ul>

<button onclick=”addItem()”>Add Item</button>

<script>
function addItem() {
const newItem = document.createElement(‘li’);
newItem.textContent = ‘New Item’;

const itemList = document.getElementById(‘itemList’);
itemList.appendChild(newItem);
}
</script>
</body>

In the example, clicking “Add Item” runs addItem() to add a new item directly to the real DOM. Try it out to see the performance, especially with multiple additions. This direct manipulation can cause slowdowns, especially in apps with frequent updates or lots of data. That’s where the Virtual DOM excels, offering a more efficient way to update the UI.

Cross-browser compatibility

A significant challenge in cross-browser compatibility arises from variations in support for DOM elements and attributes among different browsers.

React addresses this challenge through its synthetic event system. SyntheticEvent acts as a wrapper around native browser events, ensuring consistent behaviour across diverse browsers. React’s synthetic events provide a unified approach to handling browser events.

// Example code using React’s synthetic events
import React from ‘react’;

const handleClick = (event) => {
// Prevent the default behavior of the click event
event.preventDefault();

// Access event properties such as target and currentTarget
console.log(‘Clicked element:’, event.target);
};

const Button = () => {
return (
<button onClick={handleClick}>Click me</button>
);
};

export default Button;

In this example, we use React’s synthetic event system for the onClick event handler. When the button is clicked, handleClick is called with a synthetic event object that includes properties like target and currentTarget, along with methods to prevent default behaviour.

React’s synthetic events abstract away browser-specific event handling details, ensuring consistent and maintainable code. This simplifies cross-browser compatibility testing and reduces the risk of bugs due to inconsistent event behaviour.

Before going deeper on the workings of virtual DOM, we need to understand what document fragment means.

Document Fragment

A DocumentFragment in the DOM is a lightweight container that lets you group DOM nodes like elements and text nodes without adding them to the main DOM tree. It acts as a temporary container for manipulating and creating multiple elements before adding them to the main document.

DocumentFragment objects are handy for optimising performance when handling complex DOM manipulations. Instead of adding elements directly to the main document one by one, which can cause reflows and repaints, you can first add them to a DocumentFragment, make all the necessary changes, and then append the DocumentFragment to the document in one go. This reduces performance overhead.

Here’s a basic example of how you might use a DocumentFragment:

// Create a new DocumentFragment
const fragment = document.createDocumentFragment();

// Create multiple elements and append them to the fragment
const div1 = document.createElement(‘div’);
div1.textContent = ‘First div’;
fragment.appendChild(div1);

const div2 = document.createElement(‘div’);
div2.textContent = ‘Second div’;
fragment.appendChild(div2);

// Append the fragment to the main document
document.body.appendChild(fragment);

Major advantages:

Batched updatesMemory efficiencyNo redundant renderingReact’s virtual DOM is like an upgraded version of the document fragment idea.

How the Virtual DOM Works

The virtual DOM works by creating a lightweight copy of the actual DOM, which it maintains in memory. When changes are made to the UI, React first updates this virtual representation instead of directly modifying the real DOM. Then, it compares the updated virtual DOM with the previous version to identify the minimal set of changes needed to update the real DOM. Finally, React applies these changes efficiently, resulting in faster rendering and improved performance.

Here’s a simple example to illustrate how the virtual DOM works

const element = React.createElement(
“div”,
{ className: “my-class” },
“Hello, world!”
);

This creates a React element that represents a <div> element with a className of my-class and the text content Hello, world!.

{
$$typeof: Symbol(react.element),
type: “div”,
key: null,
ref: null,
props: {
className: “my-class”,
children: “Hello, world!”
},
_owner: null,
_store: {}
}

React.createElement creates virtual elements, while document.createElement creates real elements in memory. React’s virtual DOM represents a tree structure of elements and is compared to the previous tree to determine minimal updates needed. This is called reconciliation process.

React typically re-renders a component and its children when its state changes, even if props remain the same. This can cause unnecessary re-renders and impact performance, especially in complex UI’s. Developers can optimize performance by managing re-renders carefully, using techniques like memoization and component structuring to prevent unnecessary updates throughout the application.

Conclusion

In conclusion, the React virtual DOM revolutionizes web development by optimizing UI updates and performance. Through efficient reconciliation, React minimizes unnecessary rendering, enhancing responsiveness. While it’s a powerful tool, developers should mitigate potential issues like unnecessary rerenders with strategies such as memoization. Overall, the React virtual DOM empowers developers to build fast, scalable, and maintainable web applications.

References

Fluent ReactReact Docs

I read, write about low level tech details. Please reach out to me for any feedback or tech explorations!

https://www.linkedin.com/in/itherohit/

https://itherohit.dev/

Inside React: The Virtual DOM was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.

​ Level Up Coding – Medium

about Infinite Loop Digital

We support businesses by identifying requirements and helping clients integrate AI seamlessly into their operations.

Gartner
Gartner Digital Workplace Summit Generative Al

GenAI sessions:

  • 4 Use Cases for Generative AI and ChatGPT in the Digital Workplace
  • How the Power of Generative AI Will Transform Knowledge Management
  • The Perils and Promises of Microsoft 365 Copilot
  • How to Be the Generative AI Champion Your CIO and Organization Need
  • How to Shift Organizational Culture Today to Embrace Generative AI Tomorrow
  • Mitigate the Risks of Generative AI by Enhancing Your Information Governance
  • Cultivate Essential Skills for Collaborating With Artificial Intelligence
  • Ask the Expert: Microsoft 365 Copilot
  • Generative AI Across Digital Workplace Markets
10 – 11 June 2024

London, U.K.