A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://18.react.dev/blog/2022/03/08/react-18-upgrade-guide below:

How to Upgrade to React 18 – React

March 08, 2022 by Rick Hanlon

As we shared in the release post, React 18 introduces features powered by our new concurrent renderer, with a gradual adoption strategy for existing applications. In this post, we will guide you through the steps for upgrading to React 18.

Please report any issues you encounter while upgrading to React 18.

Note

For React Native users, React 18 will ship in a future version of React Native. This is because React 18 relies on the New React Native Architecture to benefit from the new capabilities presented in this blogpost. For more information, see the React Conf keynote here.

Installing

To install the latest version of React:

npm install react react-dom

Or if you’re using yarn:

Updates to Client Rendering APIs

When you first install React 18, you will see a warning in the console:

React 18 introduces a new root API which provides better ergonomics for managing roots. The new root API also enables the new concurrent renderer, which allows you to opt-into concurrent features.

import { render } from 'react-dom';

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

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

import { createRoot } from 'react-dom/client';

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

const root = createRoot(container);

root.render(<App tab="home" />);

We’ve also changed unmountComponentAtNode to root.unmount:

unmountComponentAtNode(container);

root.unmount();

We’ve also removed the callback from render, since it usually does not have the expected result when using Suspense:

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

render(<App tab="home" />, container, () => {

console.log('rendered');

});

function AppWithCallbackAfterRender() {

useEffect(() => {

console.log('rendered');

});

return <App tab="home" />

}

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

const root = createRoot(container);

root.render(<AppWithCallbackAfterRender />);

Note

There is no one-to-one replacement for the old render callback API — it depends on your use case. See the working group post for Replacing render with createRoot for more information.

Finally, if your app uses server-side rendering with hydration, upgrade hydrate to hydrateRoot:

import { hydrate } from 'react-dom';

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

hydrate(<App tab="home" />, container);

import { hydrateRoot } from 'react-dom/client';

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

const root = hydrateRoot(container, <App tab="home" />);

For more information, see the working group discussion here.

Note

If your app doesn’t work after upgrading, check whether it’s wrapped in <StrictMode>. Strict Mode has gotten stricter in React 18, and not all your components may be resilient to the new checks it adds in development mode. If removing Strict Mode fixes your app, you can remove it during the upgrade, and then add it back (either at the top or for a part of the tree) after you fix the issues that it’s pointing out.

Updates to Server Rendering APIs

In this release, we’re revamping our react-dom/server APIs to fully support Suspense on the server and Streaming SSR. As part of these changes, we’re deprecating the old Node streaming API, which does not support incremental Suspense streaming on the server.

Using this API will now warn:

Instead, for streaming in Node environments, use:

We’re also introducing a new API to support streaming SSR with Suspense for modern edge runtime environments, such as Deno and Cloudflare workers:

The following APIs will continue working, but with limited support for Suspense:

Finally, this API will continue to work for rendering e-mails:

For more information on the changes to server rendering APIs, see the working group post on Upgrading to React 18 on the server, a deep dive on the new Suspense SSR Architecture, and Shaundai Person’s talk on Streaming Server Rendering with Suspense at React Conf 2021.

Updates to TypeScript definitions

If your project uses TypeScript, you will need to update your @types/react and @types/react-dom dependencies to the latest versions. The new types are safer and catch issues that used to be ignored by the type checker. The most notable change is that the children prop now needs to be listed explicitly when defining props, for example:

interface MyButtonProps {

color: string;

children?: React.ReactNode;

}

See the React 18 typings pull request for a full list of type-only changes. It links to example fixes in library types so you can see how to adjust your code. You can use the automated migration script to help port your application code to the new and safer typings faster.

If you find a bug in the typings, please file an issue in the DefinitelyTyped repo.

Automatic Batching

React 18 adds out-of-the-box performance improvements by doing more batching by default. Batching is when React groups multiple state updates into a single re-render for better performance. Before React 18, we only batched updates inside React event handlers. Updates inside of promises, setTimeout, native event handlers, or any other event were not batched in React by default:

function handleClick() {

setCount(c => c + 1);

setFlag(f => !f);

}

setTimeout(() => {

setCount(c => c + 1);

setFlag(f => !f);

}, 1000);

Starting in React 18 with createRoot, all updates will be automatically batched, no matter where they originate from. This means that updates inside of timeouts, promises, native event handlers or any other event will batch the same way as updates inside of React events:

function handleClick() {

setCount(c => c + 1);

setFlag(f => !f);

}

setTimeout(() => {

setCount(c => c + 1);

setFlag(f => !f);

}, 1000);

This is a breaking change, but we expect this to result in less work rendering, and therefore better performance in your applications. To opt-out of automatic batching, you can use flushSync:

import { flushSync } from 'react-dom';

function handleClick() {

flushSync(() => {

setCounter(c => c + 1);

});

flushSync(() => {

setFlag(f => !f);

});

}

For more information, see the Automatic batching deep dive.

New APIs for Libraries

In the React 18 Working Group we worked with library maintainers to create new APIs needed to support concurrent rendering for use cases specific to their use case in areas like styles, and external stores. To support React 18, some libraries may need to switch to one of the following APIs:

React 18 also introduces new APIs for concurrent rendering such as startTransition, useDeferredValue and useId, which we share more about in the release post.

Updates to Strict Mode

In the future, we’d like to add a feature that allows React to add and remove sections of the UI while preserving state. For example, when a user tabs away from a screen and back, React should be able to immediately show the previous screen. To do this, React would unmount and remount trees using the same component state as before.

This feature will give React better performance out-of-the-box, but requires components to be resilient to effects being mounted and destroyed multiple times. Most effects will work without any changes, but some effects assume they are only mounted or destroyed once.

To help surface these issues, React 18 introduces a new development-only check to Strict Mode. This new check will automatically unmount and remount every component, whenever a component mounts for the first time, restoring the previous state on the second mount.

Before this change, React would mount the component and create the effects:

* React mounts the component.

* Layout effects are created.

* Effect effects are created.

With Strict Mode in React 18, React will simulate 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 effect setup code runs

* Effect setup code runs

For more information, see the Working Group posts for Adding Reusable State to StrictMode and How to support Reusable State in Effects.

Configuring Your Testing Environment

When you first update your tests to use createRoot, you may see this warning in your test console:

The current testing environment is not configured to support act(…)

To fix this, set globalThis.IS_REACT_ACT_ENVIRONMENT to true before running your test:

globalThis.IS_REACT_ACT_ENVIRONMENT = true;

The purpose of the flag is to tell React that it’s running in a unit test-like environment. React will log helpful warnings if you forget to wrap an update with act.

You can also set the flag to false to tell React that act isn’t needed. This can be useful for end-to-end tests that simulate a full browser environment.

Eventually, we expect testing libraries will configure this for you automatically. For example, the next version of React Testing Library has built-in support for React 18 without any additional configuration.

More background on the act testing API and related changes is available in the working group.

Dropping Support for Internet Explorer

In this release, React is dropping support for Internet Explorer, which is going out of support on June 15, 2022. We’re making this change now because new features introduced in React 18 are built using modern browser features such as microtasks which cannot be adequately polyfilled in IE.

If you need to support Internet Explorer we recommend you stay with React 17.

Deprecations Other Breaking Changes Other Notable Changes React React DOM Server Changelog

You can view the full changelog here.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4