Ganpati
React 18 Version: What’s New!

React 18 Version: What’s New!

02 July, 2021 by img Jatin Panchal in ReactJs Development
React 18 Version: What’s New!

React 17, which was introduced in late 2020, failed to bring lots of innovative features. Rather, it emphasized enhancing the basics plus laying the foundation for future updates. All these were done to enable smooth, gradual adoption of what is going to come next.

This is how we get introduced to React 18. The plan for the subsequent version of React was announced by the React team recently, along with many upcoming features. Likewise, there was a publicly available alpha, release timeline, plus a Working Group committed to enhancing React 18.

Lots of things are happening with React at present, and therefore, let us take a look at all the declarations and some other details.

 

React 18 Working Group

Before diving into the remarkable new features, it is essential to talk about the React 18 WG (Working Group) since this type of concept has been used for the first time in the development of React.

The group’s objective is to offer feedback and make the broader ecosystem ready for the forthcoming release of React. Although it is restricted to selected members, it will be feasible for you to always check it out since the conversation is hosted through GitHub Discussions and made publicly available as well.

You will be able to come across different concepts, research findings, and feature overviews from the React team without any problem.

React 18 Working Group happens to be the first such attempt for involving the ecosystem and community builders more in the creative procedure behind the subsequent release of React.

How is it going to influence the result? We need to wait and watch.

 

React 18: Innovative Features

As compared to the earlier version, it seems that React 18 is packed with innovative features. While some are remarkable enhancements, others shine new light on the concurrent model of React. In any case, there is plenty to unpack, with many more coming down the road!

 

Automatic Batching

There are massive enhancements to automatic batching when it comes to performance.

Before the introduction of React 18, multiple state updates were already batched by React into one for reducing unwanted re-renders. Nevertheless, it took place in DOM event handlers only, and therefore, timeouts, Promises, or other handlers did not use it to their advantage.

 

const App = () => {

  const [firstCount, setFirstCount] = useState(0);

  const [secondCount, setSecondCount] = useState(0);

  const handleClick = () => {

    setFirstCount((count) => count + 1); // No re-render yet

    setSecondCount((count) => count + 0.5); // No re-render yet

    // Re-render (updates batched)

  };

  /*

  const alternativeHandleClick = () => {

    Promise.resolve().then(() => {

      setFirstCount((count) => count + 1); // Re-render

      setSecondCount((count) => count + 0.5); // Re-render

    });

  };

  */

  return (

    <div>

      <button onClick={handleClick}>Next</button>

      <span

        style={{

          color: firstCount % 2 === 0 ? "blue" : "black",

        }}

      >

        {secondCount}

      </span>

    </div>

  );

};

With the introduction of version 18, React will batch state updates irrespective of where they take place, so long as it is risk-free to do. This leads to superior performance without any extra involvement.

 

Strict Mode Changes

Next, we will mention several additions to the Strict Mode, which includes new behavior named “strict effects. This will be double-invoking effects, particularly mount as well as unmounts ones.

The extra checks are here for testing against several mount/unmounts cycles. Apart from ensuring more resilient components, it likewise corrects behavior at the time of development with Fast Refresh (when components are mounted or unmounted) plus an innovative Offscreen API, which is presently in the works.

Better performance will be enabled by Offscreen API by concealing components rather than unmounting them, maintaining the state, and still calling the effects of mount/unmount. This will play an important role in optimizing components such as virtualized lists, tabs, and so on.

 

Root API

The render function, which was available at the beginning of every React app, will be swapped by createRoot.

This new API happens to be the gateway for accessing new features of React 18. Moreover, it is provided together with legacy API for encouraging gradual adoption and ease-out prospective performance comparisons.

New root API is likewise somewhat different syntax-wise.

import ReactDOM from "react-dom";

import App from "App";

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

// Old

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

// New

const root = ReactDOM.createRoot(container);

root.render(<App />);

 

It is evident to you how your React app’s root is now separate. Being a data structure pointer connected to a DOM element, the root had been opaque to the render function’s user previously.

It is imperative to create the root using the createRoot function and call the render method on it after this. Apart from enabling new features, it is likewise simpler and clearer to update when needed.

The new API likewise modifies the way hydrate functions and render callback work. The callback argument has been removed completely since it is difficult to time it properly. Rather, you ought to use, e.g., ref callback or timeout on the root.

// ...

// Old

ReactDOM.render(<App />, container, () => console.log("renderered"));

// New

const App = ({ callback }) => {

  return (

    <div ref={callback}>

      <h1>Hello World</h1>

    </div>

  );

}

const root = ReactDOM.createRoot(container);

root.render(<App callback={() => console.log("renderered")} />);

As for hydrate, it transforms into a config option from a separate function, making it more sensible.

// ...

// Old

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

// New

const root = ReactDOM.createRoot(container, { hydrate: true });

root.render(<App />);

 

Concurrent Rendering

There is no doubt that the most significant update for React 18 is available with the “concurrent mode” or concurrent rendering, as it is now called.

The naming alteration is essential given that it helps the adoption of concurrent features to be enabled gradually. This will enable you to adopt concurrent features seamlessly without rewrites at your convenience.

 


Must Read: How to start with test cases in React using Jest?


 

New APIs

New APIs are available with new features. However, all of these happen to be opt-in and cover things such as Suspense updates, state transitions, plus new hooks when it comes to concurrent rendering.

 

  • startTransition

A new API has been introduced by React 18 for handling heavy state updates such as list filtering or data fetches. In such cases, setting the state simply will trigger updates immediately, probably slowing down the UI.

For combating this, you will come across an innovative API as startTransition function. It will be marking state updates as transitions, making it non-urgent to handle them.

import { startTransition } from "react";

// ...

// Urgent -> show updated input

setInputValue(input);

// Transition (non-urgent) -> show search

startTransition(() => {

  setSearchQuery(input);

});

startTransition will come of use when you want to keep native user input snappy as you perform non-urgent and complicated operations in the background. If the user updates the search query, that will be reflected by the input field instantly, while the earlier transaction will be canceled.

Besides startTransition, an innovative useTransition will offer info regarding whether or not the given transition is pending. It will also enable you to set an extra timeout as well.

// ...

const App = () => {

  // ...

  const [isPending, startTransition] = useTransition({ timeoutMs: 2000 });

  startTransition(() => {

    setSearchQuery(input);

  });

  // ...

  return (

    <span>

      {isPending ? " Loading..." : null}

      {/* ... */}

    </span>

  );

};

// ...

 

This information can be used by you for render loading UIs, implementing custom handling, and so forth.

 

  • useDeferredValue

The innovative useDeferredValue hook is available to us while continuing the trend of accepting value changes.

 

import { useDeferredValue } from "react";

// ...

const [text, setText] = useState("text");

const deferredText = useDeferredValue(text, { timeoutMs: 2000 });

// ...

 

A deferred version of the accepted value will be returned by the hook that will “lag” the original one. Although it is similar, it is somewhat different from the already mentioned transitions. Nevertheless, it is useful when you have to implement complicated state-based deferred behaviors.

 

  • SuspenseList

Ultimately, you will come across the new <SuspenseList> component, which helps to organize the order in which the directly-nested <SuspenseList> and <Suspense> components become revealed. In addition, this component handles cases where fetched data can arrive in random order. Because of <SuspenseList>, it is possible to keep it orchestrated while keeping the UI in check.

 

import { Suspense, SuspenseList } from "react";

const App = () => {

  return (

    <SuspenseList revealOrder="forwards">

      <Suspense fallback={"Loading..."}>

        <ProfilePicture id={1} />

      </Suspense>

      <Suspense fallback={"Loading..."}>

        <ProfilePicture id={2} />

      </Suspense>

      <Suspense fallback={"Loading..."}>

        <ProfilePicture id={3} />

      </Suspense>

    </SuspenseList>

  );

};

// ...

 

You will find more information, such as adjusting <SuspenseList> behavior with its props in the WIP (Work-In-Progress) documentation.

 

Suspense Improvements

In combination with <SuspenseList> and other concurrent rendering updates, several enhancements have been made to the general Suspense behavior.

The most significant advancement of Suspense is turning out to be a stable feature finally with massive architectural alterations under the hood along with an innovative name – “Concurrent Suspense.” Nevertheless, the terminology is used mostly for differentiating the feature versions when it comes to migration since the user-facing modifications are minimal.

The most noteworthy user-facing change is needed to render the suspended siblings of the component.

 

// ...

const App = () => {

  return (

    <Suspense fallback={<Loading />}>

      <SuspendedComponent />

      <Sibling />

    </Suspense>

  );

};

// ...


The above code, in React 17, both lead to <Sibling/> being mounted instantaneously plus its effects called, only to be concealed soon after.

This has been fixed by React 18 by not mounting the component whatsoever and first waiting for <SuspendedComponent/> to be resolved. Although this helps fix some problems regarding libraries in React ecosystem, you should not observe that much.

 

Streaming SSR

 Apart from the mentioned enhancements to Suspense, we have likewise got massive alterations to the Suspense SSR (Server-Side-Rendering) architecture. These modifications enable a couple of significant features – the usage of <Suspense> and React.lazy(), together with Server-Side-Rendering streaming of rendered HTML, plus selective hydration for commencing hydrating the application as soon as possible.

Generally speaking, lots of things are going on out there. However, you will also come across a comprehensive column on the architecture behind Suspense, and in case you are interested, you can go through it.

 

Open Source Session Replay

It might be time-consuming and challenging while debugging a web app in production, even though you might be dealing with the most recent version of React. OpenReplay happens to be an Open-source alternative to LogRocket, Hotjar, and FullStory. With this, you can monitor plus replay everything done by your users, and it depicts how your application behaves for each issue. It is like keeping the inspector of your browser open while looking over the shoulder of your user.

OpenReplay happens to be the only self-hosted and open-source alternative available, enabling you to have total control over your data.

The most advanced open-source session replay to build delightful web apps. Image Source: Github

 

OpenReplay

Happy debugging for contemporary front-end teams – Begin monitoring your web application for free.

 

Roadmap

Consequently, with all these innovative features and more available to you in the future, you are perhaps interested regarding when to use them. The good thing is that it will be possible for you to use them right now! You will already gain access to Alpha on NPM, which is updated regularly. Nevertheless, it is not yet ready for production. If you are curious, you might take it for a spin; however, it is imperative to be aware of the bugs and issues out there.

Apart from this, the React team informed that beta will be available for at least a few months following that, with RC (Release Candidate) and general obtainability both spaced out a few weeks.

This will make the earliest feasible release date at the later part of this year, and the latest is going to be the initial half of the next year.

Consequently, there is no need to worry if you do not like to upgrade to new versions constantly. It seems that React 18 is quite smooth for upgrading, and, apart from that, there is no need for you to worry regarding upgrades for some time.

 

Try it out

We will be concluding this post by looking at what has to be done for upgrading to React 18 at present. You will come across some fantastic guides on WG threads for servers as well as clients. However, to provide you with a quick overview:

 

Install:

npm install react@alpha react-dom@alpha

 

Upgrade on client

  • Allow Strict Mode for seeing additional issues
  • Switch to the innovative Root API

 

Upgrade on server

  • Switch from renderToNodeStream (deprecated) and renderToString (restricted Suspense support), to pipeToNodeWritable

 

Conclusion

There is no doubt about the fact that React 18 appears to be a fantastic release after all. It is simple to adopt, packed with lots of features, and provides more influence to the community over its development procedure, mainly because of the new Working Group.

Concurrent rendering happens to be the most significant star of the show. You will be getting better performance and more flexibility with only one modification at the root of your React application. This is the thing that we are looking forward to the most, along with innovative APIs.

Want to build secure and scalable web app development solutions in React ?  We at Rlogical Techsoft offers React.JS  development service is focused on an exclusive web application development framework for creating secured and scalable solutions for customers across the globe.

Our company’s expert Hire ReactJS Developers are known to provide on-time solutions according to the requirements of your projects, which include app development, and customization.

Looking for Web & Mobile App Development Services?

 

Also Reads:

– EmberJs Vs. ReactJs: Everything You Need to Know
– Best 9 Examples of Websites Built with ReactJs
– Top 10 React Component Libraries 2021

 

 

 

img

Jatin Panchal

Jatin Panchal is Founder & Managing Director of Rlogical Techsoft Pvt. Ltd, a custom web & mobile app development company specialized in Outsourcing Web Development Services, Android, iOS and IoT App development.

Get in Touch

Contact Us

    Input Captcha Here: captcha

    sprite_image.png?v=1713546140USA

    3728 N Fratney St Suite 213, Milwaukee, WI 53212, United States

    Sales Executive: +1 414 253 3132

    Contact Email: [email protected]

    sprite_image.png?v=1713546140UK

    5 Kew Road, TW9 2PR, London

    Contact Email: [email protected]

    sprite_image.png?v=1713546140 INDIA (Head Office)

    701 & 801 Satkar Complex, Opp Tanishq Showroom,Behind Lal Bungalow, Chimanlal Girdharlal Rd, Ahmedabad, Gujarat 380009

    Rahul Panchal: +91-9824601707
    Jatin Panchal: +91-9974202036

    Contact Email: [email protected]

    sprite_image.png?v=1713546140 JAPAN

    301 1-28-21 Hayabuchi, Tsuzuki-ku, Yokohama-shi, Kanagawa 224-0025, Japan

    Contact Email: [email protected]

    sprite_image.png?v=1713546140 Australia

    Suit 3, Level 27, 1 Farrer Place Sydney NSW 2000

    Contact Email: [email protected]