Everything You Should Know About React 18
Tags: webdev, react, javascript
Published: 2022-02-02 12:13:10

---
title: Everything You Should Know About React 18
published: true
date: 2022-02-02 11:36:40 UTC
tags: webdev, react, javascript
canonical_url: https://www.syncfusion.com/blogs/post/everything-you-should-know-about-react-18.aspx
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qnl1om3i8k12zt7waybi.png
---

[React](https://en.wikipedia.org/wiki/React_(JavaScript_library) "Wikipedia page for React") is an open-source, JavaScript front-end library for building user interfaces. It works fast, is easy to learn, and is efficient especially in creating scalable and reusable UI components.

The React team announced the [release plan](https://reactjs.org/blog/2021/06/08/the-plan-for-react-18.html "The Plan for React 18 blog") for the upcoming stable version of React 18. Now, it is in beta.

In this article, we are going to discuss some of the marvelous feature updates for React version 18 with code examples.

## Introducing the new root API

A **root** in React refers to the top-level data structure that renders a tree. In React 18, we will have two root APIs: the legacy root API and new root API.

### Legacy root API

The legacy root API is the existing API called with the **ReactDOM.render** method. It will create a root running in **legacy** mode, which is similar to usage in React version 17. Before moving React 18 to the production, a warning will be added on the usage of the legacy root API. It will gradually enforce the usage of the new root API. The legacy root API will be deprecated in upcoming versions.

Refer to the following code example.

```js
import * as ReactDOM from 'react-dom';
import App from 'App';

const container = document.getElementById(‘root’);

// Initial render.
ReactDOM.render(<App tab="home" />, container);

// During an update, React will access the container element again. 
ReactDOM.render(<App tab="profile" />, container);
```

### New root API

The new root API will be invoked with the  **ReactDOM.createRoot** method. To use it, first, we have to create the root through the **createRoot** method with the root element as an argument. Then, we call the  **_root.render_**  method and pass the app component as the parameter. By using the new root API, we can use all the enhancements and concurrent features available in React 18.

Refer to the following code.

```js
import * as ReactDOM from 'react-dom';
import App from 'App';

// Create a root.
const root = ReactDOM.createRoot(document.getElementById('root'));

// Initial render: Render an element to the root.
root.render(<App tab="home" />);

// During an update, there's no need to access the container again since we have already defined the root instance. 
root.render(<App tab="profile" />);
```

### Changes in hydrate method

The  **hydrate**  method is similar to the render method. But it helps to attach event listeners to the HTML elements within the containers that are rendered by the **ReactDOMServer** method on the server side.

React 18 replaces this **hydrate**  method with the **hydrateRoot** method.

Refer to the following code example.

```js
import * as ReactDOM from 'react-dom';

import App from 'App';

const container = document.getElementById('app');

// Create and render a root with hydration.
const root = ReactDOM.hydrateRoot(container, <App tab="home" />);
// Unlike the createRoot method, you don't need a separate root.render() call here.
```

### Changes in render callback

The render callback is removed from the new root API. But we can pass it as property to the root component.

Refer to the following code example.

```js
import * as ReactDOM from 'react-dom';

function App({ callback }) {
 // Callback will be called when the div element is first created.
 return (
 <div ref={callback}>
<h1>Hello </h1>
 </div>
 );
}
const rootElement = document.getElementById("root");

const root = ReactDOM.createRoot(rootElement);
root.render(<App callback={() => console.log("renderered")} />);
```

## Improvement in automatic batching

The batching feature in React 18 merges multiple state updates into a consolidated single rerender for improved performance. For instance, if we update more than one state value in a simple function handler. Then, React 18 will batch these updates into a single update and rerender the app only once instead of calling the render method multiple times.

This will considerably improve the app’s overall performance. It also prevents components from rendering with incomplete state updates where only one state variable is updated, which may lead to irrelevant behavior in the app.

Refer to the following code example.

```js
function App() {
//Declaring state values.
  Const [count, setCount] = useState(0);
  const [flag, setFlag] = useState(false);

// Change state on button click.
  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>
  );
}
```

React 18 will automattically batch all the state updates, irrespective of where they originate. Therefore, if any update is inside a timeout, promise, native event handler or any other event, the React 18 version will batch it in the same way as updates inside React events. This will further improve the performance of the app and lead to fewer rerenderings of the components compared to the previous React versions.

Refer to the following code.

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

  function handleClick() {
    fetchSomething().then(() => {
      // React 18 and later versions batch these state updates with single rerendering.
      setCount(c => c + 1);
      setFlag(f => !f);
      // React will rerender once at the end (that's batching!)
    });
  }

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

### Disable automatic batching

Sometimes, we need to immediately rerender the component after each state change. In that scenario, use the **flushSync** method to disable the automatic batching.

```js
import { flushSync } from 'react-dom'; // Note: react-dom, not react

function handleClick() {
  flushSync(() => {
    setCounter(c => c + 1);
  });
  // React has updated the DOM by now.
  flushSync(() => {
    setFlag(f => !f);
  });
  // React has updated the DOM by now.
}
```

## Suspense

We can accomplish server-side rendering in React by rendering all the components on the server first. Then, we have to send the results as HTML elements to the browser.

In the browser, React will load JavaScript as usual. Then it will connect the HTML elements generated from the server with the JavaScript and hydration logics.

The server-side rendering (SSR) allows us to see the page content before the JavaScript bundle loads and runs.

The suspense feature will delay the rendering of components in React. It was first introduced in React version 16.6 with certain limitations and basic support for **suspense** rendering.

**React 18’s** stable version will support the full-fledged suspense feature based on the concurrent feature, along with the following:

- **Delayed transition:** Instructs the components to wait for the data to be resolved before proceeding with a new state transition.
- **Placeholder throttling** : Reduces UI thrash by throttling the appearance of nested place holder and successive placeholder components.
- **SuspendList:** Helps suspend many components by arranging them in the order in which these components need to be revealed to the user.

React 18 handles suspense differently from the previous versions. This seems to be a breaking change. But with the [automatic batching](https://github.com/reactwg/react-18/discussions/21 "Automatic batching for fewer renders in React 18 GitHub demo"), the impact of the change is minimum. It will not affect the migration process of the app to React version 18 significantly.

Earlier, the suspense feature in React 16 and 17 was called **legacy suspense.** The enhanced suspense in the React 18 is called **concurrent suspense**.

In general, both the legacy and concurrent suspense features offer the same basic user experience, apart from resolving the **ComponentThatSuspends** method, as in the following example.

```html
<Suspense fallback={<Loading />}>
  <ComponentThatSuspends />
  <Sibling />
</Suspense>
```

This example is a simple explanation of how a suspense component will work in the older and new React 18 versions:

- The legacy suspense will immediately mount the Sibling component to the DOM. Also, its lifecycle hooks/effects will be fired. It won’t wait for the **ComponentThatSuspends** to be resolved.
- The concurrent suspense won’t mount the Sibling component to the DOM and its lifecycle hooks/effects will not be fired until the **ComponentThatSuspends** is resolved **.** This new enhancement will resolve all the existing issues in the legacy suspense.

## Concurrency

Concurrency allows you to execute multiple tasks at the same time. For instance, let’s take a standard React app. While executing an animation action in a component, concurrency will allow UI interaction with the other React components at the same time.

Previously, only one  **setState**  update was possible at a time and all the updates had the same priority. The new concurrent feature with the [**startTransition**  ](https://github.com/reactwg/react-18/discussions/41 "startTransition feature in React 18 demos on GitHub")API will mark all the updates as non-urgent. Based on the given priority, React will interrupt them or put them on hold.

**Note:** There will be no out-of-the-box breaking changes in the component behavior related to concurrency in React 18. So, we can choose whether to use it or not.

## GitHub reference

For more details, refer to the following GitHub references:

- [New Suspense SSR Architecture in React 18](https://github.com/reactwg/react-18/discussions/37 "New Suspense SSR Architecture in React 18 demos on GitHub")
- [Five significant features of React 18](https://github.com/reactwg/react-18/discussions/46 "Demos for five significant features of React 18 on GitHub")
- [Concurrent React for Library Maintainers](https://github.com/reactwg/react-18/discussions/70 "Concurrent React for Library Maintainers demos on GitHub")

## Conclusion

Thanks for reading! The upcoming React 18 stable version will bring an exciting new set of features for the developer community. The main focus is on concurrency and gradual up-gradation to the newer version. Since it is still in beta, the React team created a  [working group](https://github.com/reactwg/react-18/ "React 18 Working Group on GitHub") to prepare the ecosystem for the smooth transition to the new version.

Syncfusion [React JS UI components](https://www.syncfusion.com/react-ui-components "Syncfusion React UI Components") will always be compatible with the latest React versions. We will include support for React 18 after it becomes production-ready.

For existing customers, the newest Essential Studio version is available for download from the [License and Downloads](https://www.syncfusion.com/account/downloads "License and download page of Essential Studio") page. If you are not yet a Syncfusion customer, you can try our 30-day [free trial](https://www.syncfusion.com/downloads "Free evaluation of the Syncfusion Essential Studio") to check out the available features. Also, check out our demos on [GitHub](https://github.com/syncfusion "Syncfusion examples on GitHub").

You can contact us through our [support forums](https://www.syncfusion.com/forums "Syncfusion support forum"), [support portal](https://support.syncfusion.com/ "Syncfusion support portal"), or [feedback portal](https://www.syncfusion.com/feedback/react "Syncfusion Feedback Portal"). We are always happy to assist you!

## Related blogs

- [Perform CRUD Operations in a React Data Grid Using Redux: A Complete Guide](https://www.syncfusion.com/blogs/post/how-to-perform-crud-operations-in-a-react-data-grid-using-redux-a-complete-guide.aspx "Perform CRUD Operations in a React Data Grid Using Redux: A Complete Guide blog")
- [Develop a Flight Tracker Application with React Gantt Chart](https://www.syncfusion.com/blogs/post/flight-tracker-application-with-react-gantt-chart.aspx "Develop a Flight Tracker Application with React Gantt Chart blog")
- [Use Syncfusion’s React Rich Text Editor with React-Redux Form](https://www.syncfusion.com/blogs/post/how-to-use-syncfusions-react-rich-text-editor-with-react-redux-form.aspx "Use Syncfusion’s React Rich Text Editor with React-Redux Form blog")
- [Unit Testing in React with Jest and Enzyme Frameworks](https://www.syncfusion.com/blogs/post/unit-testing-in-react-with-jest-and-enzyme-frameworks.aspx "Unit Testing in React with Jest and Enzyme Frameworks blog")