Understanding React Virtual DOM

React is javascript library to build UI application. React is popular and used by many organisations for the development.

Why React is Famous

React is famous because of many features like virtual DOM, routing, lightweight library, modular development and many more. Today we will see virtual DOM topic and this makes react a unique library.

Virtual Document Object Model (DOM)

The Document Object Model (DOM) is a structure of an HTML . Every node is the tree is an element.

When an user action triggers the event, an event updates DOM , now to display correct HTML , DOM needs to do some calculation called as reconciliation . Such operations are performance heavy and applications performance becomes lousy.

Virtual DOM is copy of DOM , which is first updated and the compared against the DOM and only that part is updated which needs to be updated.

As you can see in the below diagram , when action is triggered in the App, Virtual DOM is changed.

Now in second step, Virtual DOM does the reconciliation first and checks the difference with real DOM , and updates the DOM instead of doing direct updates to DOM and only changed part is updated and not entire DOM

Benefits

  • Performance efficient
  • Consistent programming interface across browsers.
  • Only Delta is updated against Full DOM.

Verify if only updated part is re-rendered

Below code is javascript file out of entire project. Entire project setup can be found here at github.

console.log("---loading script js ----");

const jsContainer = document.getElementById('jscontainer');

const reactContainer = document.getElementById('reactContainer');

const render = () => {


  jsContainer.innerHTML = `
    <div class="demo">
        Hello Javascript
        <Input/>
        <p>${new Date()}</p>
     </div>
`;

  //note the difference , in native JS we use strings and in React we use //Objects


  ReactDOM.render(
    React.createElement(
      "div", {
        className: "demo"
      },
      "Hello React",
      React.createElement("input"),
      React.createElement("p", null, new Date().toString())
    ),
    reactContainer
  );
}

setInterval(render, 1000);
console.log("completed");

As you can see, we have created a Date element and rendered forcefully every 1 second. One is normal HTML and other is using react. In Normal HTML we have string (innerHTML) and in React we have objects. Now these objects are important in reconciliation and virtual DOM updates.

The below image explains the behaviour of delta updates. You can also see video but in case you tube is blocked you can see the images descriptions.

Video showcase for delta updates

Conclusion

  • Virtual DOM is key differentiator in react
  • Virtual DOM is performance efficient
  • It updates only delta part in DOM
  • It helps to achieve great UX in Single Page Application.

Javascript IIFE (Immediately Invoked Function Expressions)

What is IIFE

Immediately invoked function expression (IIFE) is a function as expression which is executed immediately after creation. Wikipedia reference – here . The IIFE name is given by Ben Alman in his blog.

Why we need IIFE

  • Javascript variables when created are by default assigned to global namespace when not in blocks/function
function merge(firstArgument, secondArgument){
	return firstArgument + secondArgument;
}

if you define such function then it is by default assigned to global namespace i.e window in case of browser. Let’s check the output.

As you can see when we call window.merge it works as expected and this is same for variables defined outside functions. Those are also attached to global state.

Now this has some problems

  1. Too many global variables and functions results in inefficient memory management.
  2. Name collision .

One way of solving this issue is using IIFE feature. Let’s take a look .

Syntax

The common syntax is as below but note that arrow function or function with variable names as works.

(function(){ /Your code goes here... })();

Now let's convert our code to IIFE .
(function merge(firstArgument, secondArgument){
	console.log(firstArgument + secondArgument);
})('Wealth Management', 'Investment Banking');

Wealth ManagementInvestment Banking

With this way you can achieve memory management and also avoid collision of functions and variables names in global scope.

To cross verify we can try calling window.merge function and let’s see if we can get it for selection.

As you can see the function is not available at global state.

Conclusion

If you want to reduce memory footprints and avoid global state traffic then use IIFE feature.

Happy Learning !

ECMAScript 2023

ECMAScript is language specification developed by Ecma International. It’s international standard for scripting languages like JavaScript(JS).

It provides certain rules and guidances for syntax, behaviour etc like any other programming language (sql etc).

Javascript is not only limited to browsers but also to backed systems like node js and reactive native for mobile apps.

ECMAScript now early releases the features and let’s take a closer look at 2023 release.

Official Website https://tc39.es/ecma262/2023/

Announcement on June 27 , 2023 as below from official ECMAScript page.

Features :

Following methods on Array.prototype

  • toSorted
  • toReversed
  • with
  • findLast
  • findLastIndex 

Now let’s take a look at each of these methods.

  • Array.prototype.toSorted()

The toSorted()returns a new array with the elements sorted in ascending order.

As you can see below output is sorted in natural order.

const regions = ["Europe", "APAC", "BeneLux", "USA", "DACH", "ROE"];
const sortedValues = regions.toSorted();
console.log("SORTED -- ",sortedValues); 
console.log("INPUT-----",regions); 

SORTED --  (6) ['APAC', 'BeneLux', 'DACH', 'Europe', 'ROE', 'USA']
INPUT----- (6) ['Europe', 'APAC', 'BeneLux', 'USA', 'DACH', 'ROE']
  • Array.prototype.toReversed()

The toReversed() returns a new array with the elements in reversed order.(As name suggests).

const regionsForReversal = ["Europe", "APAC", "BeneLux", "USA", "DACH", "ROE"];

console.log(Array.prototype.toReversed.call(regionsForReversal));
 (6) ['ROE', 'DACH', 'USA', 'BeneLux', 'APAC', 'Europe']

  • Array.prototype.findLast()

The findLast()will provide first matching value in reverse order. Let’s take a look at an example.

const regionsForFindLast = ["Europe", "APAC", "BeneLux", "USA", "DACH", "ROE"];

const countryWithThreeLetters = regionsForFindLast.findLast((element) => element.length === 3);

console.log("countryWithThreeLetters", countryWithThreeLetters);
countryWithThreeLetters ROE

You can find all the examples related to this blog here at github.

Conclusion

It’s highly recommended to read recent trends in any technology as some features might help you to solve your problems which you are trying to solve using your own way or libraries.