React 18 : Must to know Features

What's new in react 18 ? That you can't afford to miss.

React 18 : Must to know Features

React 18

I am excited to tell you about amazing changes and features that are introduced as feature in the React 18.So the update is totally based on improving the performance of your web app . My favorite was Suspense . Give it a read to find you favorite but also if you wanna increase your knowledge on the React Internal functioning give it a read.

First I am gonna discuss a mandatory change to be made in the code . Then we will discuss about the features in the React 18 . So we should start now.

Mandatory Change in the code.

In React 17 we use to code like below in index.js

Import ReactDOM from 'react-dom';
import App from 'App';

const container = document.getElementById('app');

ReactDOM.render(<App />, container);

But here's we are suppose to write the code in React 18

import ReactDOM from 'react-dom';
import App from 'App';

const container = document.getElementById('app');

// create a root
const root = ReactDOM.createRoot(container);

//render app to root
root.render(<App />);

Automatic Batching

This is an interesting feature to know about In order to understand this first we should know about What is batching ?

Batching

We all know that on every state update a react application re-renders but batching helps to update the two states or more than one state updates with each other when they have to be updated on single react DOM event . So Batching was always there in react but it was only for the react DOM events only.

For ex-

<button onClick={ ( ) =>{
setState("Akshat");
setCount(20); } }> Submit </button>

So Batching helps a lot in making our app performance better and here comes the Automatic Batching.

Automatic Batching is super set of the Batching , where batching was just for the react DOM events but now it doesn't matter where the batching originates from like updates inside of timeouts, promises, native event handlers or any other event will batch the same way as updates inside of React events.

Use Id Hook

Very interesting new hook which is very easy to use .So the use case for this is-

1) , where the for attribute must be equal to the id attribute of the related element to bind them together. 2) aria-labelledby, where the aria-labelledby attribute could take multiple ids.

Example-

import { useId } from 'react';

const Comp1 = () => {
  const id = useId();
  return <div>Comp1 id({id})</div>;
};

const Comp2 = () => {
  const id = useId();
  return (
    <>
      <div>Comp2 id({id})</div>
      <label htmlFor={`${id}-1`}>Label 1</label>
      <div>
        <input id={`${id}-1`} type="text" />
      </div>
      <label htmlFor={`${id}-2`}>Label 2</label>
      <div>
        <input id={`${id}-2`} type="text" />
      </div>
    </>
  );
};

Concurrency

Think of it with example in real life a driver can't drive two cars at the same time . It was same prior to React 18 rendering was a single, uninterrupted, synchronous transaction and once rendering started, it couldn’t be interrupted.

But React 18 can help driver to drive two cars at the same time , that means when the other car is stuck in traffic he can drive the other one .What exactly happens is react 18 is concurrent rendering React can interrupt, pause, resume, or abandon a render. This allows React to respond to the user interaction quickly even if it is in the middle of a heavy rendering task.

useTransition

This hooks helps us in prioritizing the state updates by delaying the state updates which need not be updated quickly . React updates are classified in two ways-

1) Urgent Updates-They reflect direct interaction, such as typing, clicking, pressing, dragging, etc. 2) Transition Updates-They transition the UI form one to another .

const [isPending, startTransition] = useTransition();

isPending - It is the boolean value which will be changing on the updates.

startTransition - Its a function in which we write a call back and a state update which we want to be delayed.

Suspense

My hero indeed I feel it will be yours too. So Suspense is basically a component provided by the react . It was available in earlier versions too but now its more advanced and we are gonna know about it .

With the help of this we need not to have separate states for the loading this is the magic of Suspense.

Here is the code provided for the same where there is app file we have the given code-

import "./styles.css";
import Coins from "./Coins";
import { Suspense } from "react";
export default function App() {
  return (
    <div className="App">
      <Suspense fallback={<p>...loading</p>}>
        <Coins />
        <Coins />
        <Coins />
        <Coins />
        <Coins />
      </Suspense>
    </div>
  );
}

Coins.js

import useSWR from "swr";
const fetcher = (...args) => fetch(...args).then((res) => res.json());

const Coins=()=>{
  const { data, } = useSWR(
    "https://www.binance.com/api/v3/ticker/24hr",
    fetcher,
    {suspense:true}
  );
  return (
  <div>
    {data?.map(coin=><p>{coin.symbol}</p>)}
  </div>
  )
}
export default Coins;

So , while the code has been fetched and rendered on the UI the fallback will show something till the data has been fetched same we use to do with the "isLoading" state. With the help of useSWR we are auto handling the suspense you can read about it here useSWR. But the matter of the fact is the readability of the code increases with less state which also keeps the re-rendering in check.

Conclusion

Writing code in react is one thing and writing optimized and performance oriented code is another focus on using the proper hooks to make your app fast at the same time by taking care of the re-renders on state updates. These tools are pretty powerful if configured properly you can make a properly rendering react web app which will be fast on client side . Happy Coding.