React 18

Learn via video courses

Overview

React has released React 18, its most recent version. In contrast, to React 17 features, the most recent version contains unique functionalities to get over the drawbacks of the older version. To improve performance and simplify things for developers, React 18 includes a few of the best possible dependencies available.

Introduction

React is a JavaScript front-end library that creates creative user interfaces using various components. It continuously monitors your updates and makes the necessary adjustments. React assists developers in debugging their code on a wide scale.

React 18 has introduced some interesting new advancements. A gradual adoption plan was promised by the React developers when React 18 was first announced. After a year, they have finally accomplished this, and you may update your app to the most recent version.

There are some breaking changes in React 18 depending on the way you use it. Overall, however, it also includes out-of-the-box performance enhancements, such as batching more frequently by default, which eliminates the need for manually batching updates to the application or library code.

Therefore, let's take a closer look at some of the most significant updates that Facebook's team has introduced.

What’s Coming in React 18?

When it was launched, the new features in React 18 were new APIs (like startTransition), out-of-the-box enhancements (like automatic batching which is discussed in a later section), and a new streaming server renderer with built-in support for React. lazy.

These capabilities are made feasible via a newer opt-in mechanism that is introduced in React 18. React can prepare numerous UI versions simultaneously because of a feature known as concurrent rendering.

Although much of this change takes place in the background, it opens up new opportunities to enhance your app's actual and perceived performance.

If you've been keeping up with our study on React's future, you may be aware of something called "concurrent mode" or that it could cause your app to break. The upgrading strategy has been revised in response to the community feedback. Rather than an all-or-nothing "mode", concurrent rendering will be enabled only for updates triggered due to one of the new features. In reality, this means you'll be able to use React 18 without rewriting anything and experiment with the new features according to your speed.

A Gradual Adoption Strategy

The concurrency in React 18 is opt-in, therefore component behavior hasn't undergone any substantial breaking changes right out of the box. Anyone can easily upgrade to React 18 with little or no modifications to their application code.  We believe that several users will easily upgrade to React 18.

At Facebook, they successfully released concurrent functionality to tens of thousands of components, and based on their observations, the majority of React components "simply work" with no additional modifications.

New Features of React 18

Automatic Batching

Automatic batching is a feature of React 18. Consider the scenario when you are baking pizza for dinner. To maximize your grocery trip, you would write a list of all of the ingredients you require, go to the store, and purchase all of your ingredients in one trip.

That is batching. Without batching, you will begin to prepare a meal, realize you were missing an ingredient, run to the store to grab it, return home, resume preparation, discover you were missing yet another item, run back to the store...and go crazy.

Batching in React helps in reducing the count of re-renders that occur when a state changes, as when you use setState. Previously, React used event handlers to batch state updates.

Example:

Outside of event handlers, however, state updates were not batched. The state updates wouldn't be batched, for example, if you were performing a promise or making a network call.

This is not effective, as you can see. Automatic batching is a new feature in React 18 that enables any state modifications to be batched, including those made within promises, setTimeouts, and event callbacks. As a result, React has to perform a lot less background work. Before re-rendering, React shall wait for one micro-task to finish.

Transitions

Transitions are a useful tool for identifying UI improvements that don't require immediate resources.

For instance, when you enter a typeahead field, two things happen a blinking cursor that provides visual feedback of the text you are typing and a search function that looks for the data you are typing in the background.

It is necessary and important to provide the user with a visible response. Because searching is not as urgent, it can be classified as non-urgent.

Transitions are the name for these non-urgent changes. React will determine which updates to prioritize by classifying non-urgent UI changes as "transitions". As a result, rendering optimization and the elimination of stale rendering are made simpler.

Updates included in the startTransition  are treated as non-urgent updates, and they will be interrupted if more important updates like key presses or clicks occur. If a user interrupts a transition (for instance, by typing many characters in a line), React will discard any stale rendering work which was not completed and render only the most recent update.

New Suspense Features

Suspense allows you to declare the loading status for a portion of the component tree that isn't yet available to be displayed declaratively:

In the React programming model, suspense brings the UI loading state  to the status of a first-class declarative concept.

The suspense was released in a limited version a few years ago. But when rendering on the server, it wasn't supported at all and the only use case that was supported was code splitting with React.lazy.

Suspense server support was implemented in React 18 and its capabilities were increased using concurrent rendering techniques.

In React 18, the suspense works best when used in combination with transition API. React won't allow already-visible content to be replaced by a fallback if you suspend during one transition. Instead, React will wait until sufficient data has loaded before rendering to avoid an undesirable loading state.

New Client and Server Rendering APIs

With the release of React 18, the APIs were redesigned for client and server rendering. With these adjustments, users are now able to continue utilizing React 17's older APIs while upgrading to React 18's new APIs.

React DOM Client:

Now the react-dom/client allows you to export these additional APIs:

  • createRoot:
    A new technique for creating a root for rendering or unmounting. It should be used instead of ReactDOM.render.  Without it, new features of React 18 won't function.
  • hydrateRoot:
    A new method for hydrating a server-rendered application. It should be used instead of ReactDOM.hydrate.  alongside the new React DOM Server APIs.  Without it, new features of React 18 won't function.

If you wish to be informed when React recovers from problems while rendering or hydration for logging, you can use the new onRecoverableError option, which is supported by both createRoot and hydrateRoot. React will utilize the console or reportError by default in older browsers.

React DOM Server:

These new APIs can be exported from react-dom/server and include full server-side support for streaming Suspense:

  • renderToPipeableStream: used in Node environments for streaming.
  • renderToReadableStream: for use in current edge runtime environments.

The existing renderToString function is still operational, although it is discouraged.

New Strict Mode Behaviors

A functionality that enables React to add and delete UI elements while maintaining state is something the React community is trying to offer in the future. React should be able to instantly display the previous screen, for instance, when users tab away from one screen and back. React would do this by unmounting and remounting trees with the same component state as before.

This feature will improve the performance of React apps right out of the box, but it asks for components to be resistant to effects been mounted and destroyed numerous times. Most effects will function normally without any adjustments, but some other effects require that they are mounted or destroyed just once.

To help identify these issues,  React 18 adds a new development-only check to Strict Mode. Every time a component is mounted for the first time, the new check would automatically unmount and remount each component, returning it to its previous condition on the second mount.

New Hooks

  • useId:
    useId is a new hook that creates unique IDs on the client and server while preventing hydration issues (this issue is caused by the use of a certain library or application code that depends on a part that could be different between pre-rendering and the browser). It is most helpful when connecting component libraries with accessibility APIs that need unique IDs. This fixes a problem that was present in React 17 and before, but it becomes even more crucial in React 18 due to the way the newer streaming server renderer produces HTML out-of-order.

  • useTransition:
    Some state updates can be marked as not urgent using usetransition and starttransition. Updates to other states are automatically regarded as urgent. React will allow non-urgent state updates (like rendering a list of search results) to be interrupted by urgent state updates (like changing a text input).

  • useDeferredValue:
    You can postpone re-rendering a non-urgent portion of the tree with useDeferredValue. Although it is comparable to debouncing, there are several advantages over it. The deferred render will be attempted by React as soon as the initial render appears on the screen because there is no set amount of time for the delay. Deferred renders can be interrupted and do not block user input.

Conclusion

  • React is a JavaScript front-end library that creates creative user interfaces using various components.
  • React 18 includes out-of-the-box performance enhancements, such as batching more frequently by default, which eliminates the need for manually batching updates to application or library code.
  • Batching in React helps in reducing the count of re-renders that occur when a state changes, as when you use setState.
  • Transitions are a useful tool for identifying UI improvements that don't require immediate resources.
  • Also transitions are the name for these non-urgent changes. React will determine which updates to prioritize by classifying non-urgent UI changes as "transitions".
  • Suspense allows you to declare the loading status for a portion of the component tree that isn't yet available to be displayed yet.
  • According to the developer's requirement, React provides a few predefined hooks to carry out particular tasks. Here are a few recently released react hooks: useId, useTransition, and useDeferredValue.