React.js Deep Dive as a beginner

React.js Deep Dive as a beginner

·

10 min read

Say you have decided to learn React JS.

You started looking for a tutorial, found one and created a todo list App. Great start! Now Let's react in depth.

What is React & Why to use ❓

React is an Open Source project created by Facebook, It is one of the most popular JavaScript library with over 187k stars on GitHub which is used to build user interfaces on the font end.

But before jumping into react let's see why you should use react over vanilla JavaScript or any other library/frameworks.

In a typical JavaScript application to render dynamic content to the browser we need two things, Data and a HTML template string something like this 👇

// Data
const time = new Date().toLocalTimeString();

// Template String
const clockTemplate = `
    <div>
        <span>${time}</span>
    </div>
`;

then we combine both to get the final output to give it to the browser to render and display.

// final output
const clockTemplate = `
    <div>
        <span>5:19:45 PM</span>
    </div>
`;

// giving the final output to the browser
document.getElementById("clockEle").innerHTML = clockTemplate;

The browser creates a DOM Structure of this final output and render it.

software.hixie.ch_utilities_js_live-dom-viewer_.png

Lets assume our Data changes very frequently and We need to update our view to this new Data. To do that we need to again combine the HTML template string with the Data to produce the new final output and give it to the browser to render where browser will create a new DOM structure.

function tick(){
  // Data
  const time = new Date().toLocalTimeString();

  // Template String
  const clockTemplate = `
    <div>
        <span>${time}</span>
    </div>
  `;

  // giving the final output to the browser
  document.getElementById("clockEle").innerHTML = clockTemplate;
}

setInterval(tick, 1000);

with the above method you'll see that the entire div element gets re-rendered.

ezgif.com-gif-maker (1).gif

there's nothing wrong about it but doing this rendering operation inside the browser is very expensive because browser has to go through a sequence of steps each time it has to render the new DOM structure. and for a bigger application this is very significant.

But if we try to do the same thing with React, you'll see some major difference.

import React from "react";
import ReactDOM from "react-dom/client";

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

function tick() {
  const time = new Date().toLocaleTimeString();

  const clock = (
    <div>
      <span>{time}</span>
    </div>
  );

  root.render(clock);
}

setInterval(tick, 1000);

In this case only the elements with the data being changed gets a re-render.

ezgif.com-gif-maker (2).gif

We will understand how react is able to do this in later part, this being said it is not the only reason to use React over any other library or framework. there are some other good reasons like

React is declarative

What does it mean? In programming sense Declarative usually defined as

"telling what to do instead of how to do it".

Normally when you write a JavaScript application, You write a bunch of code to select some elements and then you actually change those elements like removing or changing the innerText or insert some new HTML to it. All of this done through events and not declaratively.

React being declarative we just tell react what do we want the DOM to look like and let the react handle it. We write the code that we want and React is in charge of taking our declared code and performing all of the JavaScript/DOM steps to get us to our desired result. We don't have to worry about how the different elements currently in the web page have to change or which ones have to be removed or inserted. React will efficiently manipulate the DOM for us.

React is component-based

React.js introduced a concept called Component-Based-Architecture, a method for encapsulating individual pieces of a larger user interface into self-sustaining, independent micro-systems.

You can think of a component as a small feature that makes up a piece of the user interface. Components represents specific screens or elements. Each react app is nothing but composition of many components.

Components can also refer to other components in their output. This lets us use the same component abstraction for any level of detail. Components let you split the UI into independent reusable pieces and think about each piece in isolation.

1651672554784 (2).jpg

In React, You can write a component in an ES6 class syntex or as Js function.

// Componenet as ES6 class
class HelloMessage extends React.Component {
  render() {
    return <div>Hello {this.props.name}</div>;
  }
}

// Component as Js function
function HelloMessage(props){
  return <div>Hello {props.name}</div>;
}

Class-based components were widely used approach to creating components in React if an app required the state to be used. However, React has evolved and introduced Hooks in version 16.8 by which we can make functional components stateful as well and therefore everyone is switching towards it and I'll also suggest you to consider functions and hooks instead of classes. As the future updates could be not supported by class-based components.

How React actually works ❓

Before diving into how react works first let's look at how to set up react to work with.

There are a few ways to set up React, And as a beginner you should use Create React App. If you have followed any tutorial on react beginners, most probably you have already used it.

Create React App is a comfortable environment for learning React, and is the best way to start building a new single-page application in React.

It sets up your development environment so that you can use the latest JavaScript features, provides a nice developer experience, and optimizes your app for production. You’ll need to have Node >= 14.0.0 and npm >= 5.6 on your machine.

It will create a live development server, use Webpack to automatically compile React, JSX, and ES6. auto-prefix CSS files and use ESLint to test and warn about mistakes in the code.

To set up create-react-app, run the following code in your terminal, one directory up from where you want the project to live.

npx create-react-app my-app
cd my-app
npm start

Once that finishes installing, move to the newly created directory and If you look into the project structure, you'll see a /public and /src directory, along with the regular node_modules, .gitignore, README.md, and package.json.

In /public directory, our important file is index.html, It contains only a single div with an id root, which is called as a “root” DOM node because everything inside it will be managed by React DOM.

The /src directory will contain all of our React code.

If you look at the ./src/index.js file, You'll see we are importing two modules React and ReactDOM

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);

React on its own is just a library that allows us to define components, elements and so on and it does the diffing part as well (will talk about it later). It isn't platform specific and it doesn't take care of the rendering. Rendering is handled by the packages called renderers like ReactDOM and React Native.

Basic concepts of React

React root

The react-dom/client package provides client-specific methods used for initializing an app on the client.

The following methods can be used in client environments:

  • createRoot()
  • hydrateRoot()

createRoot() creates a React root for the supplied container and return the root. The root can be used to render a React element into the DOM with render:

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);

In our case, We give the div element from the index.html as a container to the createRoot() method and Render the <App/> component as a user defined element.

React element

The imported React module has a method called createElement() which creates and return a new React element of the given type. It takes a type argument, a props argument and any react elements as children.

The type argument can be either a tag name string (such as 'div' or 'span' ), a React component type (a class or a function), or a React fragment type.

React.createElement("h1", {
  className: "greeting"
}, "Hello, world!");

We know that root.render() method takes a React element and renders it. But in our case we put <App/> inside the render method which looks like HTML syntex but it is neither a string nor HTML. It is called JSX ( JavaScript XML ) , and it is a syntax extension to JavaScript.

Babel compiles JSX down to React.createElement() function calls.

// JSX
<div>
  <span>{time}</span>
</div>

// Compiled down function call
React.createElement("div", null, React.createElement("span", null, time));

// the second argument is null because we are not providing any props

then the React.createElement() function call returns object similar to the object below. these are called react elements. Unlike browser DOM elements, React elements are plain objects, and are cheap to create. React elements are the smallest building blocks of React apps.

{
   $$typeof": Symbol("react.element"),
   type: "h1",
   key: null,
   ref: null,
   props: Object { className: "greeting", children: "Hello, world!" }
}

So What we come to know is that a React element is an object representation of a DOM node.

React component

If you look at ./src/app.js file, You will see something like this

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

this is a simple React functional component and it is returning JSX, And we know JSX got compiled down to React.createElement() function calls which return React Elements. hence, React components also return React Elements. But instead of a single react element we can say that React components encapsulates a DOM tree.

VirtualDOM

As we know React components encapsulate a DOM tree and Each react app is nothing but composition of many components. All React does is create a tree of React elements, this process is extremely fast as React elements are just simple JavaScript objects.

React keeps this tree of elements in the memory and this is called the Virtual DOM. The next thing to do is to sync the virtual DOM with the real DOM.

On the initial render React has to insert the full tree of elements into the real DOM.

All of this is happening when we call the render() method in the ./src/index.js file

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);

React generates the tree by starting at top in this case the <App/> component and recursively moving to the very bottom level of the component composition.

Now, Let's try to understand how react solved the re-rendering issue that we faced during the typical JavaScript application demonstration.

Reconciliation

Normally When Data changes we recombine the new Data with the HTML template string and pass the new generated output to the browser, Where browser will create a new Browser DOM and renders any new data to the DOM even if data is similar to previous ones.

But we know that React does things a little differently,

First it creates a new virtual DOM which is extremely fast, Then it compares the new virtual DOM with the previous one and finds the smallest number of operations to transform one tree into the other. This is done by Diffing Algorithm.

The cool fact is all these comparisons take place in the memory and nothing is yet changed in the Browser. After comparing, React goes ahead and creates a new Virtual DOM having the changes. Then it updates the Browser DOM with the least number of changes possible without rendering the entire DOM again.

Suppose we have new data similar to the previous one, Virtual DOM compares previous and new structures and sees that it has no change, so nothing gets re-rendered to the Browser.

This process makes React work faster and it is known as Reconciliation, It is the process through which React updates the Browser DOM.

This is everything you should know about how react works as a beginner But, there are some other stuffs that you should know like how react state and lifecycle methods work but I'll cover these in a separate blog.

Hope you find this blog helpful, thanks for Reading 👋

Did you find this article valuable?

Support Goutam's Blogs by becoming a sponsor. Any amount is appreciated!