Basic concepts of JSX and Virtual DOM every React JS developer should know

JSX and Virtual DOM are the two main concepts of React JS that powered React JS to reach its unique stage. Today we will discuss these two concepts in brief.

What is JSX?

JSX is an acronym of JavaScript XML. JSX is nothing but a syntactic sugar of creating React Element. It allows us to write HTML-like syntax in JavaScript function.

Why JSX?

Before going into detail about why JSX is used, let’s take a look at how HTML renders by the browsers.

We all know that browsers can only understand HTML code. But how does the browser run the HTML code under the hood and display the amazing pages? Basically, when the browser renders the HTML code, it passes them through HTML parser and creates an object-like structure called DOM tree (DOM stands for Document Object Model). The next step of rendering is Attachment. In the attachment phase, all the style rules are attached with DOM tree and sent to the Render tree. Finally, Render tree pains the element on the screen, and we can see them.

When browser converts the HTML to DOM tree, it used a document method called createElemet() for every HTML element. For example –

const root = document.getElementById("root");
const h2 = document.createElement("h2");
h2.innerText = "Hello, world!";

In the above code, first, we have created an HTML element using document.createElement() method. The browser does the same for every HTML element on the page while parsing a page. When browser’s HTML parser finds any HTML element, it converts it to DOM element using document.createElement method. So, HTML is nothing but a syntactic sugar of createElement method, which allows us to create elements simply and concisely.

Similarly, React JS has a virtual DOM. It needs to create React Elements for its virtual DOM. We can create react elements using React.createElement method. But it is tedious to create multiple or nested elements by calling the React.createElement method again and again. JSX made a developer’s life easy and simple by enabling us to create react elements using simple HTML-like syntax. See the following examples –

To display hello h2 (wrapped in h2) and hello h3 (wrapped in h3) on the web page under root div using React.createElement we have to write –

const root = document.getElementById("root");

// Only using React.createElement
const element =  React.createElement('div', null, [
   React.createElement("h2", null, "Hello h2"),
   React.createElement("h3", null, "Hello h3"),

ReactDOM.render(element, root);

But we can do the same using JSX like the following –

const root = document.getElementById("root");

// Using JSX
const element = <div>
   <h2>Hello h2</h2>
   <h3>Hello h3</h3>

ReactDOM.render(element, root);

Virtual DOM and Diffing algorithm

We have discussed the browser DOM in short in the JSX section. React JS stands on an idea of something similar to browser DOM called virtual DOM. Virtual DOM is a mirror copy of browser DOM. When we run a react app in the browser, React JS creates a copy of the browser DOM and holds it in the memory.

The reason React creates a virtual DOM is to identify any change of state on the DOM elements and update it to the UI quickly and efficiently.
When we change any element in the browser DOM, it needs to re-render the whole DOM tree. Modern single-page applications can have hundreds of thousands of states. Sometimes, it is costly to detect any state change and update the UI accordingly. React brought a revolution in this case of handling vast amounts of state very quickly and efficiently.

How actually React JS handle this using virtual DOM? Well, let me explain.

As I have mentioned earlier, React creates a virtual representation of browser DOM when the application renders for the first time on the browser. If any of the elements or states change in the page, react create another copy of the previous virtual DOM without re-rendering the browser DOM and compare the changes between the previous virtual DOM and newly created virtual DOM using diffing algorithm. React made it very efficient and quick to find out the difference between them because there is no UI painting involved there. After identifying the difference, React only update the differents part of the browser DOM without re-rendering the whole page.

Though React is not the best solution for all use cases, it performs better compared with vanilla JS or using jQuery, where needs to deal with a massive number of states like SPA because of its virtual DOM concepts. So we should keep a clear-cut concept of React virtual DOM as a React JS developer.

Source link

🧬 JSX at lowest level

this post is a precursor for upcoming JSX posts

So we all heard that JSX is a specific JavaScript syntax that is used by React to render components. Well, I would say JSX is just HTML in JavaScript. Or Java-Script-Xml 😂 because HTML is a sibling of XML and children of SGML. Or maybe is just Java-Script e-X-tended.

When people ask me what is React? I tell them that React is just JavaScript functions that return HTML. And this is basically a template engine.

function Component() 
/* ^^^^^^^^^^^^^^^^ */
/*   ^^^ JavaScript */

  return <div className="yay">lorem ipsum</div>
         /* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ */
         /*       ^^^ HTML                   */

Draft: JSX Specification

Ok, but HTML syntax is allowed only in the DOM, browser JavaScript does not support it. So it means we need to compile that to something that is supported by the browser.

JSX is just some syntactic sugar that is compiled to valid JavaScript.

What is JSX Pragma?

At the moment it compiles to something like this.

function Component() 
  return React.createElement("div",  className: "yay" , "lorem ipsum");

As you can see the <div> syntax sugar is compiled to React.createElement. That’s why we need to have React imported at the top of the file. Otherwise we will get an runtime error that React cannot be found.

import React from 'react'

Production createElement implementation
Development createElement implementation

But that was until React v17.0, Babel v7.9 and TypeScript v4.1, because after that they decided to extract JSX creation in a separate factory detached from React, and it is imported automatically 🚀 🚀 🚀

Production jsx implementation
Development jsx implementation

Are you still here? Let’s go deeper 😀

man hard working

So if everything is configured correctly, this example:

function Component() 
  return <div className="yay">lorem ipsum</div>

Will be compiled to something like this:

import  jsx  from "react/jsx-runtime";
function Component() 
  return jsx("div",  className: "yay", children: "lorem ipsum" );

In a future stable release (already), React will support a group of new functions for instantiating JSX elements as an alternative to the legacy general-purpose React.createElement function. This will allow optimizing them better in the future.

So we see that <div> syntax sugar is compiled to jsx(...) at build time, but what happens with this call at runtime? Well, let’s console.log this call.

When React calls Component

function Component() 
  return jsx("div",  className: "yay", children: "lorem ipsum" );

It will return:

function Component() 
    $$typeof: Symbol('react.element'),
    props:  className: 'yay', children: 'lorem ipsum' ,
    type: "div",

Actually there is an open RFC that it seems that in the end React team will decide to compile directly JSX down to this object that is returned.

And for example if we want to render our Compnent to the DOM. Having this call

ReactDOM.render(<Component />, rootElement);

It will be compiled to this:

   $$typeof: Symbol('react.element'), type: Component ,

In the end our components are just some functions that return some objects that represent what we want rendered. So when we create our components, what we return is not what is rendered. ReactDOM calls our function components with some props, see this object definition that is returned and decides what and how to render on the screen. And JSX? JSX is just some syntax that is familiar to us because we know HTML.

But now we know that till our component goes down to ReactDOM it passes through some steps and transformations.

Also JSX is no more a React only thing, it’s already used in a lot of projects, like vue, stenciljs, dom-chef, and many others…

Have a feeling that noone is reading these articles 😀
Thanks reader if you are here! ♥️

Cover Photo by Alexandre Debiève on Unsplash

Source link