React v18: What You Need to Know

Andrew Allison
Level Up Coding
Published in
5 min readFeb 22, 2022

--

Photo by Lautaro Andreani on Unsplash

Since it was first open-sourced in 2013, React.js has quickly risen to become the most popular frontend framework in the industry. I was fortunate enough to be starting my career in web development right around this time. Anyone who has been along for the ride since the beginning will know that it has improved vastly and continues to integrate functionality that previously required additional libraries. On the eve of the newest release of React.js we can take a quick look at what to expect.

Timeline

As of Feb 2022, React.js v18 has no specific release date yet. All communication surrounding the release can be currently found on the React.js website and working group on Github. We do know however, that we can expect minimal breaking changes to component behavior in comparison to past releases. One direct quote from the working group even said:

“We expect that many users will be able to upgrade within a single afternoon”

Version 18 is following a standard software release cycle pattern (starting with Alpha and ending with General Availability (GA)) in which we are currently awaiting the first Release Candidate (RC):

React v18 Release Timeline

New Features

Suspense for Data Fetching

This feature, along with Server Side Streaming / Selective Hydration, are in my opinion the biggest features of this new release of React.js. Suspense was already a part of React before this release. It’s a Higher Order Component that allows you to display something while your app waits for an asynchronous API call to fetch some data. Suspense for Data Fetching is a new feature that allows you to use Suspense to declaratively “wait” for anything else, including lazy loading another component:

const ChildComponent = React.lazy(() => import('./Child'));

<Suspense fallback={<Skeleton />}>
<ChildComponent />
</Suspense>

Data fetching libraries can take advantage of the new APIs to support Suspense for Data Fetching. It’s expected that Relay, Facebook’s GraphQL data fetching library, will be the only one to fully support this on the day React v18 goes GA. However, experimental support is available in many data fetching libraries, though the experimental syntax is subject to change.

Server Side Streaming / Selective Hydration

The term “Server Side Streaming” can be a bit confusing as it has nothing to do with the server sending new chunks of markup to the client as it loads. Previously, React would hydrate an entire page at once. If one component was taking longer to load its data, that would block everything. With Server Side Streaming, if you are using Suspense with a component, React will wait to hydrate the component until the loading condition is satisfied, but can hydrate the rest of the page.

Transition

This is another huge feature of React 18. With this, developers can easily solve issues with frequent updates. The useTransition hook helps developers to easily identify which action is blocking the main thread. For example, if you have an <input /> element, you can update the input’s value and search results simultaneously. If a more critical update comes, the updates passed into useTransition will be marked as non-urgent. This will help keep your app responsive even during large screen updates:

...const [resource, setResource] = useState(0);const [startTransition, isPending] = useTransition({
timeoutMs: 3000
});
return (
<>
<input
onChange={(e) => {

/**
* Wrapping the state update in `startTransition`
* which is a function returned by `useTransition`
*/
startTransition(() => {
const nextUserId = getNextId(e.target.value);
setResource(fetchProfileData(nextUserId));
});
}}
/**
* `isPending` is a boolean returned by the useTransition hook
* indicating whether we are waiting for the transition to
* finish or not
*/
disabled={isPending}
/>
<ProfilePage resource={resource} />
</>
);
...

Automatic Batching

This is when you have several useState hooks updating inside one event handler. In React v18 there will be improved performance when doing this out-of-the-box called auto-batching. This will eliminate the rendering of components “Half-Finished”.

...const [count, setCount] = useState(0);
const [flag, setFlag] = useState(false);
const handleClick = () => {
fetchSomething().then(() => {
setCount(c => c + 1);
setFlag(f => !f);
});
};
return (
<div>
<button onClick={handleClick}>Next</button>
<h1 style={{ color: flag ? "blue" : "black" }}>
Count: {count}
</h1>
<h1 style={{ color: flag ? "blue" : "black" }}>
Flag: {`${flag}`}
</h1>
</div>
);
...

Root API

In React 18 two different root APIs will be deployed from the react-dom package. There will be a legacy root API (ReactDOM.render) and the new ReactDOM.createRoot. The legacy API will eventually be deprecated it will trigger warnings.

Change this:

Legacy API

To this:

New API

New Hooks

  • useSyncExternalStore — will replace the existing useMutableSource (Redux users would likely never use the useMutableSource hook directly. They would use a hook provided by Redux that uses useMutableSource internally)
  • useId — helps avoid hydration mismatches (think that annoying warning about adding a key attribute to each component in an array). Normally, I would use a library like uuid for this but React 18 has it built-in now
  • useInsertionEffect — works roughly like useLayoutEffect for CSS libraries that generate new rules on the fly and insert them with <style> tags into the DOM. This would be most CSS-in-JS libraries designed specifically for React today.

How to try these new features today

The list above is not a holistic list of all the new features but it is a good start. To get started using these features today you can take a look at this demo for Auto Batching:

To install and try out the the Beta release package with a new create-react-app use the following command:

$ npm install react@18.0.0-beta-24dd07bd2-20211208 react-dom@18.0.0-beta-24dd07bd2-20211208

Level Up Coding

Thanks for being a part of our community! More content in the Level Up Coding publication.
Follow: Twitter, LinkedIn, Newsletter
Level Up is transforming tech recruiting ➡️ Join our talent collective

--

--