React 18: An Introduction To The Latest Version

React 18: An Introduction To The Latest Version

An introduction to the latest launch from React along with an exploration of some interesting features

The latest version of React has been announced recently with multiple out-of-the-box improvements and a new concurrent rendering opt-in mechanism. The new version focuses on a gradual adoption strategy which means that you can upgrade to React 18 with no or minimal changes to your code. Well, that’s something. Isn’t it?

But before we get started with new features there is something that you should know about and that is React 18 Working Group (WG). Introduced for the first time in React development, the goal of this group is to prepare the ecosystem for the gradual and smooth adoption of the upcoming release through the usage of existing applications and libraries. The discussions are done publicly through Github Discussions and you can find all information in the aforementioned link. The most amazing part of this new release is that it makes us feel like we are part of this journey of research on upcoming new features. As you must have realized that React 18 has a lot to offer, so let’s dive in and get the fun started.

Automatic Batching

Batching is a process in which React groups sends multiple state updates into a single re-render to avoid unnecessary re-renders. Before React 18, React used to batch the states which can only happen in DOM event handlers which resulted in the missing out on other state updates like in promises and setTimeouts amongst other handlers. But in version 18, automatic batching will batch all the state updates, whether it is happening inside the promises widget or in setTimeouts, as long as it is safe to do so which results in an improved performance. Let's look at the following code for reference:

function App() {
  const [count, setCount] = useState(0);
  const [flag, setFlag] = useState(false);

  function handleClick() {
    fetchSomething().then(() => {
      // React 17 and earlier does NOT batch these because
      {/* they run *after* the event in a callback, not *during* it */}
      setCount(c => c + 1); // Causes a re-render
      setFlag(f => !f); // Causes a re-render
    });
  }
  return (
    <div>
      <button onClick={handleClick}>Next</button>
      <h1 style={{ color: flag ? "blue" : "black" }}>{count}</h1>
    </div>
  );
}

If you don’t want to batch, you can opt out of batching by using ReactDOM.flushSync().

Concurrent Rendering

Without any doubt, concurrent rendering is the biggest update for React 18. This means that you can gradually adapt the concurrent features with minimal or no changes to your code at your own pace.

startTransition

This feature focuses on keeping the app more responsive even during large screen updates. With this feature, users can will be able to mark state updates as transitions which will then be handled as non-urgent. Let us take a search input field as an example. So two things would be happening happening in this scenario where one field would show the user typed input in the UI while the other is searching for the data that is typed by the user.

Now, showing the typed input becomes an urgent task while searching for the data is non-urgent. Hence, we would be able to mark search functionalities as transitions through which React can prioritize updates, making UI will seem more responsive. However, the updates marked non-urgent can be interfered with by other urgent updates like clicking or pressing. Use the following code to proceed:

import { startTransition } from 'react';

 {/* Urgent: Show what was typed */}
setInputValue(input);

 {/* Mark any state updates inside as transitions */}
startTransition(() => {
{/* Transition: Show the results */}
  setSearchQuery(input);
});

setTransition Vs setTimeout

  • setTimeout has a guaranteed delay while the setTransition widget depends on the other urgent tasks in hand and speed of the device.

  • User can check the status of the transition using the useTransition hook whether the given transition are pending or not.

  • setTimeout sometimes freezes the page, which is not the desired result. But that’s not the case in setTransition as the process can manually be interrupted by other urgent updates.

New Suspense SSR

This feature is for improving the performance of React server-side (SSR) rendering.

What is SSR?

SSR generates the HTML from React components on the server and sends the acquired HTML to the users. Basically, SSR lets the user see the page’s content before the Javascript bundle loads and runs. If you do not use SSR, the user will see a blank page while the Javascript loads. Some major features of SSR which makes it advantageous is the ability to stream HTML and selective hydration.

Hydration is the process of rendering components and attaching event handlers.

The picture given below depicts the whole process of fetching data from a server and displaying it in the UI:

Screenshot 2021-07-12 at 2.37.24 PM.png

Problems with SSR today

Before sending any HTML to the client, all the data needs to be collected on the server and the JavaScript code needs to load for all the components on the client's side before you start hydrating any of them. All the components need to be hydrated before a user can interact with any of them which causes problems when opting for server side rendering

Selective Hydration

React will send static HTML first like headers, sidebars, menus and will show other elements like Spinner when the HTML is streamed. For example, the comments component will become a heavy lifting component as it depends on the data from the database which makes it possible to display Spinner when it is ready. But until the JS code for the Comments section loads, we cannot start hydrating the app on the client. Well, the solution for this is our second function of SSR that we spoke about-Selective hydration.

Selective hydration prioritizes which component needs to be loaded first and the components with user interaction are given priority in this scenario. If the user interacts with any of the components, React will hydrate that component first. This is how a heavy component of JS doesn’t prevent the rest of the page from becoming interactive and this is the method we can use to hydrate the app before the Comment widget loads.

Conclusion

As you can see React has truly released its alpha version with this latest launch. These new features solve all of our previous issues and now you can:

  • Stream HTML before all the data is fetched.
  • Hydrate the page before all the HTML has been streamed.
  • Interact with a page before all the components are hydrated.
  • You also don’t need to hydrate components in order to interact with any other component.

So these are the amazing new features of the upcoming version. You can install the React18-alpha version from here.

Do try it out and let me know how you feel about it in the comments. Happy reading :P