Bi-monthly news update from IsDB-BISEW IT Scholarship Programme (November 2023)

Empower

 

 


We are back! Welcome to the November 2023 issue of Empower, the periodic newsletter of the IsDB-BISEW IT Scholarship Programme. This edition includes the following topics of note:

  • The Power of React’s Virtual DOM: A Comprehensive Explanation

  • Improbable Dreams – Farjana’s Story


The Power of React’s Virtual DOM: A Comprehensive Explanation

(Collected from a post on the site Syncfusion.com)

Modern JavaScript frameworks have entirely changed the way web development is done. They have provided a great abstraction by addressing common issues in browsers and enhancing performance using methodologies that were not possible through plain JavaScript.

React, one of the most popular JavaScript frameworks, is a great example. It uses something called a Virtual DOM under the hood to drastically increase performance. You have likely heard this term many times but may not truly understand how it works.

This article will discuss the virtual DOM and how it works. But to understand the virtual DOM, first, we must know how a page renders in a browser.

How does a page render in a browser?

When a browser loads any webpage, the page is loaded in multiple parts, then it is constructed in the browser and rendered.

The start-to-end process of rendering a webpage looks like this:

  1. The HTTP protocol returns data in bytes.
  2. These bytes are converted into characters, then tokens, then nodes, and then, lastly, the object model.
  3. The DOM (Document Object Model) is a tree-like structure that represents HTML. It is generated from a webpage’s HTML markup. Similarly, the CSSOM (CSS Object Model) is generated from a webpage’s CSS markup. The DOM and CSSOM are loaded independently as trees, and then they are combined into a render tree to form a webpage.

DOM and CSSOM are combined to create the render tree, source: web.dev

To construct the render tree, the browser processes each node in the DOM, looks for the node’s corresponding style in the CSSOM, and applies the style to the node. Once the final tree is formed, the page is laid out so that each node is placed in its calculated position on the screen.

Every time an HTML element is updated, a complete re-rendering process takes place.

The entire process of rendering a webpage is known as the critical rendering path. It is one of the most important considerations for SEO and web performance.

Now that we understand how a webpage is rendered in the browser, imagine a modern web application. Behind the scenes, fast DOM manipulation is happening, and the resulting frequent re-rendering heavily impacts performance. We need to find some way to address this. This is where the virtual DOM comes into play.

What is the virtual DOM, and how does it work?

One way to optimize webpage performance is by making the minimum changes possible to the DOM as infrequently as possible so that updates can be rendered quickly.

This is what the virtual DOM tries to do.

The virtual DOM is a representation of the original DOM through a JavaScript object. It is a concept that React has popularized and uses within its library to improve re-rendering performance whenever the DOM is updated. Whenever the DOM updates in React after a state change, the changes are first made to the virtual DOM.

The virtual DOM creates a snapshot (the existing state) of itself before the update. Then it compares the changes with the snapshot to determine what exactly has changed using a diffing algorithm called reconciliation.

Virtual DOM identifying changes to apply to the Original DOM

The reconciliation algorithm depends on an identifier to determine the uniqueness of each DOM element in the list. This identifier helps perform the comparison in O(n) time when it would otherwise take O(n3) time.

After reconciliation, with the help of the ReactDOM.render() method, React renders the DOM update to the original DOM. The virtual DOM helps eliminate unnecessary re-renders of DOM elements.

Each component in React can have its state, and state updates are batched in React. This helps group multiple updates in the virtual DOM so that the frequency of DOM updates can be reduced.

Let’s attain a better understanding of this with the help of the following example:

import React, { useState, useRef, useEffect } from 'https://esm.sh/react@18.2.0'

import ReactDOM from 'https://esm.sh/react-dom@18.2.0'

const App = () => {

  const [count, setCount] = useState(0);

  const timerIdRef = useRef(null);

  const onStart = () => {

     timerIdRef.current = setInterval(() => {

     setCount((prevCount) => prevCount + 1);

     }, 1000);

  };

  const onStop = () => {

      clearInterval(timerIdRef.current);

  };

  return(

     <div className="box">

       <h1>Count: {count}</h1>

       <button onClick={onStart}>Start</button>

       <button onClick={onStop}>Stop</button>

     </div>

  );

}

ReactDOM.render(<App />,

document.getElementById("root"));

In the previous code, when the Start button is clicked, a timer starts that automatically updates the state at an interval of one second.

Consider the following DOM elements:

<div className="box">

   <h1>Count: {count}</h1>

   <button onClick={onStart}>Start</button>

   <button onClick={onStop}>Stop</button>

</div>

When the state changes for the count, the virtual DOM detects the difference, and only <h1>Count: {count}</h1> is re-rendered.

Re-rendering HTML elements through virtual DOM

The virtual DOM is not a shadow DOM

Though both terms are used interchangeably often, they are completely different.

Shadow DOM is a concept that browsers use to abstract or hide the inner implementation of certain DOM elements.

For example, if you render <input type= “range”/> in the browser, you see a progress bar.

This progress bar is generated with a combination of HTML elements, but it is hidden from the end user by the browser. When you inspect the DOM, you will see <input type= “range”/> only.

Browser hiding the inner implementation of the DOM using shadow DOM

However, if you enable the shadow DOM visibility in the browser, you will be able to see all the hidden elements.

Shadow DOM visibility enabled to show the hidden elements

Conclusion

Virtual DOM is a powerful concept that React uses to overcome standard performance issues in the browser. It is not a perfect solution, and many other frameworks are working on improving it. In time, the original DOM in the browser is getting faster and will eliminate the need for virtual DOM altogether.


Improbable Dreams – Farjana’s Story

 

Name: Farjana Sharmin

ID: 1244285

Course: Database Design & Development, Round: 37

 

Farjana Sharmin works in Star Ceramics Ltd as a Senior Developer in the company's IT department. Farjana is proud to be the first female software developer at Star Ceramics. Specialising in Oracle database application development, Farjana is a graduate of the IsDB-BISEW IT Scholarship Programme.

The IsDB-BISEW IT Scholarship Programme is widely reputed for making improbable dreams come true and Farjana is a prime example. She grew up in Cumilla and obtained a BBA degree in Finance from the World University at Dhaka. She met with a serious accident right after her graduation. A complicated fracture in her leg forced her into a long period of convalescence.

Being confined to her home, Farjana had ample time to think about her future. Her search for jobs online made her realise that the employment market was extremely tough. Suitable jobs with long-term prospects were few and far between for a fresh candidate like her. However, one thing stood out in her attempts at job search and that was the multitude of job openings in the field of information technology (IT). She rightly concluded that the fast-expanding IT industry in Bangladesh offered the best chance for entry and career growth for her. But to Farjana, a career in IT seemed a far cry as she possessed no knowledge or skill in computing. That was when she learned about the IsDB-BISEW IT Scholarship Programme and its various career courses in IT.

Farjana applied for the scholarship in 2018. She was awarded the scholarship after she cleared the scholarship screening process. Within a year, she completed her allotted course on Oracle database with excellent performance. IsDB-BISEW’s job placement cell immediately placed her in a job at ATI Limited, a software development company. “My sole focus at this stage of my career was to learn as much as possible without worrying about any other factor”, said Farjana. During the COVID outbreak, Farjana changed jobs and joined Jayson Pharmaceuticals Ltd as an Oracle developer. After a one-year stay at Jayson, Farjana was offered a very lucrative job at Star Ceramics Ltd. She was the first female developer at Star Ceramics and has recently been promoted for her excellent performance. Farjana feels grateful to the IsDB-BISEW IT Scholarship Programme for transforming her career pathway and helping her become a true IT professional.

Coincidentally, Farjana is married to Shahadat, who is also a graduate of the IT Scholarship Programme. Shahadat is an Oracle developer at ERA InfoTech.

MD. SHADAT HOSSAIN KHAN