Virtual DOM: A Gentle Introduction

Virtual DOM: A Gentle Introduction

Document Object Model: Definition

The well–known DOM stands for Document Object Model. It’s basically a programming interface used in web documents. That is a representation of the page, so programs are able to change the document structure, styling, and content. The document is represented as nodes and objects so that’s what the DOM looks like. 

As it’s an object–oriented representation of the web page, it can be modified with a scripting language like JavaScript. It was meant to be accessible by any scripting language so programmers can freely manipulate the actual DOM node.

A simple example of a DOM object:

		<h1>I am the heading</h1>

Usage of DOM

It’s not hard to imagine a situation where clicking the button triggers a particular change on an actual page that we can see or multiple changes of the whole website. All of those cases are manipulations on the actual DOM of the website. Basically, all scripts that are running on the website are using the DOM.

Accessing the DOM

As the DOM API can be directly used in JavaScript, you don’t have to do anything special to begin using the DOM. When you create a script, whether inline in a <script> tag or included in the web page, you can immediately begin using the API for the document or window objects to manipulate the document.

       // run the script when the document is loaded
       window.onload = () => {

         // create some elements to include them in your DOM
         const heading = document.createElement("h1");
         const heading_text = document.createTextNode("Heading here!!");

         // append your elements to your document

Of course, this is just a simple example of the DOM usage. The only factor that can limit you is your creativity 😊.

Virtual DOM

Today we know that actions taken on the actual DOM objects are too slow for most JavaScript operations. This slowness is made even worse by the fact that most JavaScript frameworks, such as React or Vue.js, update the DOM much more frequently than they have to. As you can imagine, rendering the whole DOM tree on a very complex website every time an action is performed can be quite complicated and time–consuming for the browser engine. 

Here comes the new virtual DOM, which was popularized by React Developers to address that problem. Particularly in React, for every real DOM object, there is another, the corresponding object in the virtual DOM tree. So at this point, we can single–handedly state that every DOM object in React has its representative in virtual DOM, so the whole document is represented in its virtual reflection

This virtual reflection of DOM is basically a lightweight copy. A virtual DOM object has exactly the same properties and it’s a real substitute, but it lacks the real thing’s power to directly change what’s visible on the screen.

Shadow DOM

A very important aspect of web components is encapsulation. What this means is that we are able to keep the markup structure, styling, and behavior hidden and separate from other code on the page so the code remains nice and clean. The Shadow DOM API is a key part of this, providing a way to attach a hidden separated DOM to an element.

Shadow DOM terminology:

  • Shadow host — the regular DOM node that the shadow DOM is attached to,
  • Shadow tree — the DOM tree inside the shadow DOM,
  • Shadow boundary — the place where the shadow DOM ends, and the regular DOM begins,
  • Shadow root — the root node of the shadow tree.

We can simply affect the DOM nodes of the shadow DOM just like we do with a regular DOM. We can append children or set different attributes. The only difference is that the code that is responsible for managing shadow DOM elements can’t be used to manipulate anything outside it, allowing a handy encapsulation.

What is JSX?

The abbreviation JSX stands for JavaScript XML. In the most simple words, it’s a syntax extension for JavaScript. It allows us to directly write any valid HTML code in React (only within JavaScript code of course). It’s meant to be useful in writing any HTML templates that we can use in our React application, but it’s not a simple template language — instead, it comes with the full power of JavaScript.

It’s much faster than normal JavaScript as it performs optimizations while translating to regular JavaScript. React uses components for this purpose instead of separating the markup and logic in different files.

JSX is not only used in React. A new and nowadays very popular JavaScript framework, Vue.js, is also using this syntax.

Syntax example:

const element = <h1>Welcome your JSX code.</h1>;

In React, JSX produces elements (React.Element). The next step is to render those elements to the DOM.

React embraces the fact that rendering logic is inherently coupled with the other UI logic: how events are handled, how the state changes over time, and how the data is prepared for display.

Instead of separating technologies by putting markup and logic in separate files, React separates concerns with loosely coupled units called “components” that contain both. Taking it into consideration, the most convenient way to solve that issue is to make use of the great JSX.

As a good–to–know tip, React doesn’t force anybody to use the JSX. However, most people find it the most comfortable and suitable way to work with UI inside of the JavaScript code. It also allows React to show more useful error and warning messages.

React & JSX example:

import React from 'react';
import ReactDOM from 'react-dom';
const name = "Your Name";
const element = <h1>Hello,
{ name }. Welcome!.< /h1>;

Why Use Virtual DOM?

DOM manipulation is slow. 

That’s a fact and we all already know it. 

Manipulating the virtual DOM is much more effective. 

One of the reasons is that nothing shows up on the screen. Instead of juggling the real content of the page, we just take care of its virtual representation. Think of it as editing a blueprint instead of applying changes to the real item or project.

When you render a JSX element, every single virtual DOM object gets updated.

It might look inefficient, but the cost of re-rendering any virtual DOM object is insignificant because virtual DOM can update blazingly fast.

Once the virtual DOM is updated, React, behind the scenes, compares the virtual DOM with the snapshot of a virtual DOM that was taken just before the update. 

Then there’s a time for a process called diffing’. The process when React figures out exactly which virtual DOM objects have changed. It happens right after comparing all the changes made to virtual DOM. 

Once the ‘diffing’ process is done and React knows exactly which virtual DOM objects have been changed and how they were changed, React can update only those objects on the real DOM. It’s very important that React at this point can evaluate which exact objects are changed and can maintain updating only those objects. It of course improves the efficiency of the whole process, which makes it an extremely powerful tool.

To visualize that process we can imagine a list of items. In many scenarios, we’d like to change some values or properties, but only for one particular list–item. In our example React will be smart enough to rebuild your list–item, and leave the rest of the items alone. 

React is well–known for its performance efficiency and that’s the reason for its quite huge reputation. This is an innovative way of using the DOM and handling all manipulations that are so inefficient in the traditional way.

Key Takeaways

As a summary, here is a list of steps that happen when you try to update the DOM in React: 

  1. The whole virtual DOM is updated,
  2. The virtual DOM is compared to what it was like before the update itself,
  3. React checks which objects have been changed,
  4. Only the changed object, and nothing else, gets updated on the real DOM,
  5. Changes to the real DOM tree are applied to the screen so everyone can see them.

Looking for a reliable software development team?

We use cookies

We use cookies to make sure your website experience is as easy and as personal as possible. By accepting, you’re allowing them to do their job. Change your cookie preferences if you wish to.

Why? To analyze our visitor data, improve our website and show personalized content to our users. We want to give you a better experience of Massive Pixel Creation. Are you fine with this?