React 18 : Concurrency, Automatic Batching, Transitions & Other Updates
Tags: react, react18
Published: 2022-04-05 14:52:37

_ **Quick Summary:** _

_The much anticipated  __**React 18**__  update is here, and here is everything you need to know about &#39;What&#39;s New in React 18&#39;. Let us see the  __**latest React 18 features and changes**__  that will revolutionize how the world Reacts!_

**React v18.0**  is here after a long wait and many speculations in the React community about the major updates this version will bring to the developers&#39; community and the clients as well.

From the beginning, the React team has been very cautious about introducing these groundbreaking upgrades to the React developers at a pace that they can understand, adopt and embrace entirely. They invited a panel of experts, library authors, developers, and educators from various fields to participate in their [**React 18 Working Group**](https://github.com/reactwg/react-18) for giving inputs, providing feedback, and collaborating with them on the release. This group aims to prepare the React ecosystem for a smooth, seamless adoption of React 18 for existing libraries and applications.

Now that React 18 is finally out, there are many  **React 18 new features and changes**  that will redefine React in the future. There has been major consideration and measures taken to ensure that upgrading your current React project to React 18 doesn&#39;t break your existing code. Without further ado, let&#39;s get right into it:

> _ **Also Read:** __ _[_ReactJs Advantages and Disadvantages_](https://aglowiditsolutions.com/blog/pros-and-cons-of-reactjs/)

**1. React 18 Concurrent Mode**

This is one of the most important  **React 18 new features**  that solve an age-old ignored problem in React – concurrency. It is not exactly a feature; however, it works more like a behind-the-curtains function, that powers React to prepare various instances of your UI concurrently (at the same time). Generally, React designs APIs, and hides the implementation details from developers. They believe React developers need to focus on how using React features will help them achieve the user experience they want for their clients and React will figure out how to deliver that experience.

Although, Concurrent React is not just an implementation detail. It is a fundamental React change that updates React&#39;s core rendering model which makes it important to understand how Concurrent React works in React 18.

Before React 18, or even before upgrading to React 18 and not enabling concurrent features, updates are rendered in a single, uninterrupted, and synchronous transaction. The problem with asynchronous transactions is once you initiate an update to render, nothing can interrupt it until the result is shown on the user&#39;s screen.

This is not always the case in concurrent rendering. React can very well initiate rendering an update, pause it in middle, or abandon an already in progress rendering update entirely. React guarantees a seamless user experience and consistent UI at all times even when a render is interrupted. This enables React to create new screens behind the scenes without affecting the main thread. Hence the main thread can respond to the user input as soon as it receives it, even if it is stuck in rendering a middle to large update. This creates a seamless user experience.

Another benefit of concurrent React is the reusable state. Through concurrency, React will be able to eliminate sections of the overall UI from the users&#39; screen and add them back whenever by reusing its previous state. For instance, when a user changes tabs and returns to the original tab, React will be able to store the state of the original tab in the same state as it was before. React 18 is going to introduce a new component called \&lt;Offscreen\&gt; to implement this pattern.

> **LOOKING FOR REACT DEVELOPERS TO HIRE?**
> GET IN TOUCH TO DEVELOP HIGHLY SCALABLE WEB APP PROJECT.
> [HIRE REACTJS DEVELOPERS](https://aglowiditsolutions.com/hire-reactjs-developers/#inquire_now)

**2. Automatic Batching**

React has always used batching for grouping state updates using event handlers and inbuilt hooks. Doing so helps prevent components from unnecessarily re-render for all state updates, which results in improvised performance. Until React 17, batching was only supported for browser events. With the new React 18 release, React is launching an improved version of batching called &#39; **Automatic Batching**&#39;. Automatic Batching will enable batching for all state updates irrespective of where they&#39;re coming from with createRoot. This will include batch state updates, asynchronous operations, intervals, native event handlers, and timeouts.

**React 17 batching:**

```
functionApp(){

const[count, setCount]=useState(0);

const[flag, setFlag]=useState(false);

functionhandleClick(){

fetchSomething().then(()=\&gt;{

// React 17 and earlier versions does NOT batch these because

// they run \*after\* the event in a callback, not \*during\* it

setCount(c =\&gt; c +1);// Causes a re-render

setFlag(f =\&gt;!f);// Causes a re-render

});

}

return(

\&lt;div\&gt;

\&lt;button onClick={handleClick}\&gt;Next\&lt;/button\&gt;

\&lt;h1 style={{color: flag ?&quot;blue&quot;:&quot;black&quot;}}\&gt;{count}\&lt;/h1\&gt;

\&lt;/div\&gt;

);

}

```

Here as you can see, as React 17 and previous versions only batched updates after the event is in a callback, it sets both functions to cause a re-render, making the entire React app rerender twice separately.

However, React 18 overcame this limitation by batching updates inside of any promises, timeouts, native event handlers, or any other events just like updates inside React events were handled in React 17. This will significantly reduce unnecessary re-renders, improving application performance:

**React 18 Automatic Batching:**

```
functionApp(){

const[count, setCount]=useState(0);

const[flag, setFlag]=useState(false);

functionhandleClick(){

fetchSomething().then(()=\&gt;{

// React 18 and beyond WILL batch these:

setCount(c =\&gt; c +1);

setFlag(f =\&gt;!f);

// React will only re-render once at the end (that&#39;s batching!)

});

}

return(

\&lt;div\&gt;

\&lt;button onClick={handleClick}\&gt;Next\&lt;/button\&gt;

\&lt;h1 style={{color: flag ?&quot;blue&quot;:&quot;black&quot;}}\&gt;{count}\&lt;/h1\&gt;

\&lt;/div\&gt;

);

}

```

> _ **Also Read:** __ _[_How to Secure ReactJS App?_](https://aglowiditsolutions.com/blog/reactjs-security-best-practices/)

**Stopping Automatic Batching with flushSync()**

Now that we understand the benefits of automatic batching in reducing unnecessary rendering that was happening in React 17 and previous versions, it is also important to have a way to stop automatic batching for code that may depend on reading something directly from the DOM as soon as there is a state change. For this, React 18 has a provision of ReactDOM.flushSync() that helps developers opt-out of batching:

```
import{ flushSync }from&#39;react-dom&#39;;// Note: from react-dom, not REACT

functionhandleClick(){

flushSync(()=\&gt;{

setCounter(c =\&gt; c +1);

});

// React has updated the DOM by now

flushSync(()=\&gt;{

setFlag(f =\&gt;!f);

});

// React has updated the DOM by now

}

```

**3. Transitions**

**Transition**  is a new concept introduced in React to differentiate between non-urgent and urgent updates. It helps developers set priorities to updates they expect their users to interact with more, or want their users to have a seamless experience with.

Urgent updates reflect direct interactions like clicking, typing, pressing, and so on. Transition updates that transition the UI from one view to another. Urgent updates need an immediate response for matching the user&#39;s intuition and experience when they deal with physical objects. If there is a slight delay when they click a button, it throws them off as they expect an immediate response. Users are more patient with transition updates as they understand that their actions will not provide immediate response on screen, for instance moving from one page to another. For instance, if a user clicks a drop-down menu button, they expect the drop-down menu to appear on click, although the contents of the drop-down menu can load with a slight delay, which is natural for users to understand. Especially when you filter or sort the data according to new attributes, users will be patient with those updates.

Generally, if you want to deliver the user experience, single-user input should result in both an urgent and a non-urgent update. With React 18, developers can use start transition API inside an input event which informs React which updates are urgent and which are just &#39; **transitions**&#39;.  Let us understand how this looks in coding:

```
import{startTransition}from&#39;react&#39;;

// Urgent: Show what was typed

setInputValue(input);

// Mark any state updates inside as transitions

startTransition(()=\&gt;{

// Transition: Show the results

setSearchQuery(input);

});

```

Here updates wrapped inside start transition will be considered non-urgent and will be interrupted if any urgent update from the user&#39;s end like keypress or click comes in. If the transition gets interrupted by the user, React will abandon the mid-rendering task that wasn&#39;t finished and prioritize rendering the latest urgent update.

**There are two ways to start transitions in React 18:**
**useTransition**  – a hook used to start transitions, including a value for tracking the pending state.

**start transition**  – when hooks aren&#39;t available, developers can use this method to start transitions.

> **ARE YOU LOOKING TO HIRE REACT NATIVE DEVELOPERS?**
> Hire dedicated React Native experts from Aglowid with ample experience in delivering cost-effective cross-platform mobile app solutions.
> [HIRE REACT NATIVE DEVELOPERS](https://aglowiditsolutions.com/hire-react-native-developers/#inquire_now)

**4. React 18 Suspense Features**

**React suspense**  is a React component that helps developers suspend a component being rendered until a certain condition is met, and this displays a fallback option. The fallback option can be a string or other React component such as a spinner. Until now React Suspense would only work with dynamic importing (lazy loading).

```
import React from&#39;react&#39;;

// Dynamic import()

const CatAvatar = React.lazy(()=\&gt;import(&#39;./path/to/cat/avatar&#39;));

// Displays &quot;loading...&quot; to the user until CatAvatar

// has finished loading.

constAppContainer=()=\&gt;(

\&lt;React.Suspense fallback=&quot;loading...&quot;\&gt;

\&lt;CatAvatar /\&gt;

\&lt;/React.Suspense\&gt;

);

```

Hence, so far  **React suspense**  was being utilized to help developers present a graceful loading state to the users when they experience a delay where the network has finished loading and is executing the next chunk of JavaScript code. Through React Suspense, you could inform your users that the web app is loading the next chunk and the data will be presented to them shortly.

With React 18, developers at React decided to expand the functionality and utility of React suspense, especially integrating it with React 18&#39;s concurrent rendering features we discussed earlier. Now developers can combine React Suspense with transition API. If a transition is suspended, React will prevent the already visible content to be replaced by a set fallback. Instead, React will now delay the rendering for long enough until sufficient data gets loaded for avoiding a bad loading state.

**5. New React Strict Mode Behaviours**

Strict mode got introduced in React with the React 16.3 build. It was brought to React as a tool for identifying coding patterns that could cause problems with React&#39;s concurrent rendering APIs. It runs in development-only mode and shows them error messages or suggestions about their code, so they can refine it better. When developers add \&lt;StrictMode\&gt; to a React app, it adds a special behavior to all the components that it is wrapped around. For instance, when developers would run React in &#39; **strict mode**&#39; React would intentionally re-render all components for flushing out any unsafe effects.

With React 18, \&lt;StrictMode\&gt; will get additional behaviors and features that allow React to add or remove particular sections of the UI while preserving its state. For doing this React will mount and unmount trees using the same component state as before. This will help React performance optimization out of the box but needs the components to be resilient to the impact of being mounted and destroyed multiple times. Most effects should work without needing to make any changes but some effects assume they are destroyed or mounted once. React 18 strict modes will be able to stimulate unmounting and remounting the component in development mode:

\* React mounts the component.

\* Layout effects are created.

\* Effect effects are created.

\* React simulates unmounting the component.

\* Layout effects are destroyed.

\* Effects are destroyed.

\* React simulates mounting the component with the previous state.

\* Layout effects are created.

\* Effects setup code runs

**6. New React Hooks**

And last but certainly not least, there are new  **React hooks**!  React hooks were made available in October 2018. They provide developers with an alternative to developing class-based components and a different perspective on state management and lifecycle functions. It powers React functional components that make it possible for developers to develop an entire app with it. This helps developers execute simpler codes that implement similar functions in a faster and more effective manner. With React 18, there are many new React hooks introduced such as:

| **New React Hooks** | **Description** |
| --- | --- |
| **useId:** | It is a new hook that helps generate unique IDs on both server and client while avoiding hydration mismatches. It is mainly useful for component libraries integrating with accessibility APIs that need unique IDs. |
| --- | --- |
| **useTransition &amp; startTransition** | Allows developers to mark state updates that are not highly important or urgent. Other states are treated as important when you do so. |
| **useDeferredValue:** | Helps defer re-rendering a non-urgent part of the tree. There is no fixed delay, hence React attempts deferred rendering right after the first render is reflected on screen. This is interruptible and hence doesn&#39;t block user input. |
| **useSyncExternalStore:** | Brand new React hook that allows external stores to support concurrent reads by forcing updates to the store to be synchronous. Using with removes the requirement of using useEffect when subscribing to external data sources. |
| **useInsertionEffect:** | Another new React hook that enables CSS in JavaScript libraries to deal with performance issues of injecting styles in the render. This hook gets executed after DOM is mutated and before layout effects read the new layout. |

**Wrapping up!**

These are the latest developments and changes in React 18 that you should know about. Keep checking this space for more React 18 updates and finding out what&#39;s new in React as and when it becomes available to public.