React 18 New features

The React team recently released React V18, which came with a lot of cool new features that got us super excited. In this article, we’re going to walk you through the newest features of React!. React 18, brings immediate performance improvements such as Automatic Batching, new APIs like startTransition, and streaming server-side rendering with support for Suspense.

React 18 Concurrency

The biggest change so far in React 18 is concurrency. Concurrency is such a big deal that many of the new features of React 18 are built on its new concurrent Renderer.

But you may ask, what even is concurrency anyway?

Concurrency in programming is when multiple tasks or events are running seemingly simultaneously. Notice I did not say simultaneously. This is because the tasks run in an interwoven fashion, the device can run multiple tasks, by switching between the tasks multiple times. This differs from parallel programming, where multiple tasks are running at the same instant, by utilising separate resources, e.g., different threads, although it may seem like it.

So what does this mean for React 18?

Concurrency in React is technically not a feature, but a new core mechanism behind the scenes. It's a foundational update to React’s core rendering that allows React to run multiple tasks simultaneously, e.g., preparing multiple versions of your UI. This works by making the rendering process interruptible. Before React 18, rendered processes were uninterruptible and synchronous. This means once a rendering process begins, it cannot be stopped until the result has been returned to the user as a UI change.

React 18 allows interruptible rendering. This means a rendering process may be paused halfway through, then continued later, or even abandoned altogether. The team at React maintained a consistent UI, even if a rendering process is interrupted.

React does this by performing the DOM mutations only at the end, once the entire tree has been evaluated.

For the average developer that doesn’t want to get too deep into the weeds, this means React can prepare new screens in the background, without blocking the main thread. Allowing the UI to respond immediately to user interaction even amid a large rendering task, which creates a consistently fluid experience.

Concurrency in React is an opt-in feature, and only available when you use a feature that uses concurrency.

Transitions

A Transition is a new concept in React, used to separate urgent and non-urgent updates.

Urgent updates are updates that arise from direct interaction, such as clicking, typing, etc. These kinds of updates need an immediate response from our application to provide a smooth user experience.

A Transition is considered a non-urgent update. Transitions are updates that the user does not expect them immediately. This means a minor delay would not be an unpleasant experience and sometimes even expected. An example results from a fairly arduous task, for example, like changing an image filter.

React now allows you to define which updates are urgent and which are not urgent (Transitions).

For the best user experience, it is recommended that a single user input should cause both an urgent update and a non-urgent update (Transition). React 18 adds the new startTransiton API which you can use inside an input event to inform React which updates are urgent and which are transitions.

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

Updates wrapped in startTransition will be handled as non-urgent and will be interrupted if more urgent updates like clicks or key presses come in. If a Transition gets interrupted by the user, React will throw out the old rendering work that wasn’t finished and render only the latest update. Transitions use React's new concurrent rendering, so a transition update can be interrupted.

A homemade batch of German sugar cookies, rolled and cut into two different heart shapes, cools on a cookie rack.
Photo by Diane Helentjaris / Unsplash

Automatic Batching

Free performance is impressive, but what’s even better is free performance without us having to do any work! Automatic Batching is another performance improvement feature new in React 18. Batching is when React would group multiple state changes into a single re-render for better performance. Before, this would only have been done inside React event handlers. But now, React automatically batches state changes inside of promises, setTimeout, native event handlers and more, which were not automatically batched before.

Here's a simple example using the setTimeout method.

// Before Automatic Batching: only React events were batched.
setTimeout(() => {
  setCount(c => c + 1); //state change 1
  setFlag(f => !f); // state change 2
	// React will render twice, once for each state update (no batching)
}, 1000);

// After Automatic batching: updates inside of timeouts, promises,
// native event handlers or any other event are batched.
setTimeout(() => {
  setCount(c => c + 1); //state change 1
  setFlag(f => !f); //state change 2
  // React will only re-render once at the end (that's batching!)
}, 1000);

Server Components

A new feature called Server Components allows devs to build apps that work across the server and client. This combines the rich interactivity of client side apps with the improved performance of traditional server rendering.

New Suspense Features

React added wider support for Suspense, which lets you declaratively specify the loading state for part of the component tree, if it’s not yet ready to be displayed. In React 18, support for Suspense has been added on the server and expanded using concurrent rendering features.

New Client and Server Rendering APIs

React 18 added some new APIs for the React DOM Client and React DOM Server such as createRoot and hydrateRoot and onRecoverableError; in case you want to be notified when React recovers from errors encountered during rendering or hydration for logging.

New Strict Mode Behavior

React 18 introduces a new development-only check to “Strict Mode”. This check automatically unmount and remounts every component whenever a component mounts for the first time, keeping the state of the previous mount on the second mount. This is useful in a case where a user taps away from a screen and taps back again. This will make React be able to immediately show the results of the previous screen. React can do this by unmounting and remounting trees using the same component state as before. Before this change, React would mount the component and create the effects:

New React Hooks

React 18 adds support for a bunch of new hooks,  which we’ll do a quick rundown.

  • useId: A new hook for generating unique IDs on both the client and server, whilst at the same time avoiding hydration mismatches. This is useful for component libraries which integrate with the accessibility API that require unique IDs.
  • useTransition: The useTransition and startTransition hooks lets you mark state changes which are not urgent or “transitions' ' Other urgent state updates can now interrupt the non-urgent updates if need be.
  • useDeferredValue : This hook lets you defer re-rendering a non-urgent part of the tree. Similar to debouncing, but helpful since there is no fixed time delay, so React will attempt the deferred render immediately after the first render is shown to the user. And it's also interruptible, so doesn't block user input.
  • useSyncExternalStore: This hook allows external stores to support concurrent reads.  It does this by forcing the updates to the store to be synchronous. This removes the need for the useEffect hook when implementing subscriptions to external data sources.
  • useInsertionEffect: This hook allows CSS-in-JS libraries to address performance issues of injecting styles in the render. This is meant mostly for devs who are building CSS-in-JS libraries, and not for standard app developers.

These are some of the newest features in React V18. Want to learn how to use these and all the outstanding features to become frontend web developer? My friends at CodeDamn offer a free bootcamp that gets jobs!