Codementor Events

React 18: Things You Need To Know About React JS Latest Version

Published Jul 21, 2021
React 18: Things You Need To Know About React JS Latest Version

The most awaited version of React 18 is finally out now. Its team has finally revealed the alpha version of React 18 and its plan, though the official launch is still pending. This time the team has tried something and released the plan first to know their user feedback because the last version of React 17 was not that much appreciated among developers.

According to Front-end Frameworks Survey, React JS has ranked top in the list of most loved frameworks. Thus, the developer communities expect a bit higher from the framework, so they are less appreciative of the previous launch.
ReactJS stats.png
So, this time React 18 will be a blast. For beginners, the team is working on a new approach. They have called a panel of experts, library authors, educators, and developers
to take part in a working group. Initially, it will be a small group.

I am not a part of this release but following the team on their GitHub discussion group. After gathering the information from there, I can say that they have planned much better this time.

The Main of React 18 will be:

• Some significant out-of-the-box performance improvements
• New concurrent features
• Essential improvements in the server-side rendering area

In this write-up, I will explain the three main features that the team is introducing in React 18. So, explore the features of React 18 with me.

#1. Concurrency

React 18's central theme is concurrency. Do you know its meaning? Let me explain it to you first.

Concurrency is the ability to perform multiple tasks simultaneously. Considering the case of a standard React app, let's assume that animation is working in a component, and at the same time, a user can type or click in other components of React.
reactjs 18.png
Here, when a user is typing and clicking on buttons, animation also renders there within the React's context.

React has to handle all the function calls, hook calls, and event callbacks, some of which can even co-occur. If React gives all its time rendering animation frames, users will think that the app is stuck since it won't be reacting to their inputs.

Now React, working on a single-threaded process, has to merge, reorder and prioritize these events and functions to provide users an optimum and quality experience.

For this, React uses a "dispatcher" internally, responsible for prioritizing and requesting these callbacks.

Before React 18, users had no way to control the invocation order of these functions. But now, it's providing some control of this event loop to the user with the Transition API.

#2. Automatic Batching

When groups of React multiple state updates into one render for improved performance is called batching.

For instance, React has always batched these into one re-render if you have two state updates inside the same click event. If you are running the following code, you’ll notice that while clicking every time, React only performs one code render, though you set the state the two times:

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

  function handleClick() {
    setCount(c => c + 1); // Does not re-render yet
    setFlag(f => !f); // Does not re-render yet
    // React will only re-render once at the end (that's batching!)
  }

  return (
    <div>
      <button onClick={handleClick}>Next</button>
      <h1 style={{ color: flag ? "blue" : "black" }}>{count}</h1>
    </div>
  );
}

code snippet for state change

It is best for performance because it avoids unimportant re-renders. It also prevents the component from rendering half-finished states where a single state variable was updated only, creating bugs. You might think of a restaurant waiter who doesn't run to his kitchen when you select the first dish but waits for you to complete your order.

Though, React wasn't constant about when it batches updates. It is because React used to only batch updates during a browser event (like click), but here we're updating the state after the event has already been handled (in fetch callback):

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>
  );
}

code snippet state change in fetch

In the automatic batching (after updating your system to React 18), no matter where the states originate, it will always be re-rendered once.

In case if you don't want to batch:
Here, you have to use flash sync to re-render the component.
reactjs 18.png

#3. SSR Support for Suspense

It is an extension of Server Side Rendering (SSR) logic. In a typical React SSR application, the following steps occur:
The server retrieves the relevant data that has to be displayed on UI
The server renders the whole app to HTML and transfers it to the client in response.
The client downloads the JavaScript bundle (excluding HTML)
In the last step, the client connects the javascript logic to the HTML (known as hydration).

There is one problem with a typical SSR application that every step has to finish for the whole app at once before you could start the next step.

But now, React 18 has tried to solve this issue. <Suspense> component is revolutionized to break down the app into smaller independent units that pass through the steps mentioned above. As a result, users will see the app content quickly and start interacting much faster with it.

#4. Transition

Transition API is an incredible feature that's coming with React 18. It allows the users to solve the frequent update's issues on the large screens. E.g., Type in the input field that filters the data list. You have to solve the area's value in the state to separate the data and control the input field value. This code may look like the below code:

// Update the input value and search results
setSearchQuery(input);

Whenever a user types any character, we update the input value and use a new value to find the list and display the results. It can cause delay on the page for large-screen updates while everything renders, making other interactions or typing slow and unresponsive. Even if your list is not too long, the list items can be complex and varied on every keystroke. There you find no clear way for optimizing their rendering.

Conceptually, there is an issue of two updates that have to happen. The first one is an urgent update where you have to change the value of the input field and possibly, some UI around it. In contrast, the second one is a less urgent update to show the search results.

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

// Not urgent: Show the results
setSearchQuery(input);

Now, the new start transition API has solved this issue by allowing to mark updates as

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);
});

Summing Up!

React 17 was not able to meet the developer's community. The focus was all primarily centered on making it easier to upgrade React itself. React 18 release will be the opposite. It has a lot of features for developers.

But, yes, keep in mind that there can be changes in the final version since it is a beta release. After the release, the majority of features may orbit around concurrence. That is excellent news, as it will help the developers in improving the app speed and efficiency. With all those new tools, they can fine-tune their performance better.

If you want to know more or have any doubts, hire react developers. They will guide you better and prepare you accordingly for your upcoming project

Good Luck!

Discover and read more posts from Gerrard Cooper
get started