How to upgrade to React 18 – React Blog (2023)

This blog has been archived. Go see recent posts.

as we share inslow down the fastReact 18 introduces features powered by our new concurrent renderer, with a gradual rollout strategy for existing apps. In this post, we are going to walk you through the steps to upgrade to React 18.

Pleasereport any problemyou will find when upgrading to React 18.

Note for React Native users: React 18 will be released in a future version of React Native. This is because React 18 relies on the new React Native architecture to take advantage of the new features introduced in this blog post. For more information, seeReact Conf speech here.


To install the latest version of React:

np installreact react

Or if you are using wires:

fio to addreact react

Updates to Client Rendering APIs

When installing React 18 for the first time, you will see a prompt in the console:

ReactDOM.render is no longer supported in React 18. Use createRoot instead. Until you switch to the new API, your app will behave as if it's using React 17. Learn more:

React 18 introduces a new root API that offers better root management ergonomics. The new core API also enables a new concurrent rendering engine to enable concurrent features.

(Video) React 18 New Features, Changes & v18 Upgrade Guide

// beforematter {rendering} z "responder";untilcontainer=document.getElementById("application");rendering(<Application pato="dom" />,container);// Aftermatter {criarRoot} z "respond/customer";untilcontainer=document.getElementById("application");untilsource= criarRoot(container); // createRoot(container!) if using TypeScriptsource.rendering(<Application pato="dom" />);

we also changedisassemble or component failedTo doroot.unmount:

// beforedisassemble or component failed(container);// Aftersource.disassemble();

We've also removed the render callback as it often doesn't produce the expected results when using Suspense:

// beforeuntilcontainer=document.getElementById("application");rendering(<Application pato="dom" />,container, () => {console.Daily('rendered');});// Afterfunction Post-render callback application() { UseEffect(() => {console.Daily('rendered'); }); turn back <Application pato="dom" />}untilcontainer=document.getElementById("application");untilsource= criarRoot(container);source.rendering(<Post-render callback application />);


There is no one-time replacement for the old rendering callback API - it depends on your use case. See the working group post forReplace rendering with createRootFor more informations.

Finally, if your app uses hydration server-side rendering, updatehydrationTo dohidratoRoot:

// beforematter {hydration} z "responder";untilcontainer=document.getElementById("application");hydration(<Application pato="dom" />,container);// Aftermatter {hidratoRoot} z "respond/customer";untilcontainer=document.getElementById("application");untilsource= hidratoRoot(container, <Application pato="dom" />);// Unlike createRoot, you don't need a separate call to root.render() here.

For more information, seeworking group discussion here.


If your app doesn't work after the upgrade, make sure it's wrapped<Strict Mode>. Strict mode became stricter in React 18, and not all of its components may be immune to the new checks it adds in development mode. If removing strict mode fixes your app, you can remove it during an update and add it back (at the top or part of the tree) after fixing the issues you point out.

(Video) React 18 - Everything You Need To Know - Migrating from v17

Updates to Server Rendering APIs

In this version we are rebuilding ourreact-home/servidorAPI for full server-side SSR Suspense and Streaming support. As part of these changes, we are deprecating the old Node streaming API, which does not support server-side incremental Suspense streaming.

Using this API will now result in a warning:

  • rendering to node stream:Obsolete ⛔️️

Instead, for streaming in Node environments, use:

  • rendering to a pipeline stream:Novo ✨

We are also introducing a new API to support SSR streaming with Suspense for modern edge runtimes such as Deno and Cloudflare Workers:

  • rendering to a readable stream:Novo ✨

The following APIs will continue to work, but with limited Suspense support:

  • renderToString:Limited⚠️
  • renderToStaticMarkup:Limited⚠️

Lastly, this API will still work for email rendering:

  • renderToStaticNodeStream

For more information on changes to the server rendering APIs, see the workgroup post atUpgrading to React 18 on the server, Adetails on the new Suspense SSR architecture, EUshaundai personkeep talkingStreaming server rendering with suspensena React Conf 2021. See More

TypeScript definition updates

If your project uses TypeScript, you need to update your@types/reactEU@types/react-domdependencies for the latest versions. The new types are more secure and catch issues that were previously ignored by type checking. The most noticeable change is thatchildrenprop must now be explicitly mentioned when defining props, for example:

interface My button props {cor: corda;children?:to react.ReactNode;}

To lookRespond to a pull request for 18 entriesfor a complete list of type-only changes. It has links to sample fixes in library types so you can see how to customize your code. You can useautomatic migration scriptto help move your application code to new, safer types faster.

If you find a typo, pleasereport problemin the DefinitelyTyped repository.

automatic dosing

React 18 adds out-of-the-box performance improvements, making more batch operations by default. Batching is when React groups multiple state updates together into a new render for better performance. Prior to React 18, we only batch refreshed inside React event handlers. Updates inside promises, setTimeout, native event handlers or any other events were not wrapped by default in React:

(Video) React 18 - New Features and Changes | How to Upgrade

// Prior to React 18, only React events were bundledfunction manipulateClick() { number of settings(C =>C+ 1); set the flag(F => !F); // React will only re-render once at the end (this is batch processing!)}set time limit(() => { number of settings(C =>C+ 1); set the flag(F => !F); // React will render twice, once for each state update (no batching)}, 1000);

Getting Started with React 18zcriarRoot, all updates will be automatically bundled, regardless of their source. This means that updates inside timeouts, promises, native event handlers, or any other event will be wrapped the same way as updates inside React events:

// After React 18 updates within timeouts, promises,// native event handlers or any other events are wrapped.function manipulateClick() { number of settings(C =>C+ 1); set the flag(F => !F); // React will only re-render once at the end (this is batch processing!)}set time limit(() => { number of settings(C =>C+ 1); set the flag(F => !F); // React will only re-render once at the end (this is batch processing!)}, 1000);

This is a revolutionary change, but we hope it will result in less rendering work and therefore better application performance. To disable automatic grouping you can useFlushSync:

matter {FlushSync} z "responder";function manipulateClick() { FlushSync(() => { set the counter(C =>C+ 1); }); // React already updated the DOM FlushSync(() => { set the flag(F => !F); }); // React already updated the DOM}

For more information, seeAutomatic batch deep dive.

New APIs for libraries

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

  • useSyncExternalStoreis a new hook that allows third-party stores to handle concurrent reads by forcing store updates to sync. This new API is recommended for any library that integrates with external state in React. For more information, seeuseSyncExternalStore post reviewEUuse SyncExternalStore API details.
  • use insert effectis a new hook that allows CSS-in-JS libraries to solve style injection performance issues on rendering. Unless you've already built a CSS-in-JS library, we don't expect you to use it. This hook will work after DOM mutation but before layout effects read new layout. This solves an issue that already existed in React 17 and earlier, but is even more important in React 18 because React yields to the browser during concurrent rendering, giving it a chance to recalculate the layout. For more information, seeLibrary upgrade guide for<style>.

React 18 also introduces new APIs for concurrent rendering, such asstartTransition,use deferred valueEUusage IDabout which we write more inslow down the fast.

Strict mode updates

In the future, we would like to add a feature that will allow React to add and remove sections of the UI while preserving state. For example, when the user slides a tab away from the screen and vice versa, React should be able to immediately open the previous screen. To do this, React would detach and reassemble the trees using the same component state as before.

This feature will give React better performance out of the box, but it requires the components to be able to support multiple mounts and destruction of effects. Most effects will work without any changes, but some effects assume they are only mounted or destroyed once.

To help expose these issues, React 18 introduces a new developer-only restricted mode test. This recheck will automatically disassemble and reassemble each component whenever the component is mounted for the first time, reverting to the previous state of the second assembly.

Prior to this change, React used to assemble the component and create effects:

(Video) React 18 upgrade guide | Upgrade to react 18 and enjoy the new features!| TechHarvesting

* React assembles the component. * Layout effects are created. * Effect effects are created.

In strict mode in React 18, React will simulate disassembling and reassembling a component in development mode:

* React assembles the component. * Layout effects are created. * Effects are created.* React simulates disassembling components. * Layout effects are destroyed. * The effects are destroyed. * React simulates the component assembly with the previous state. * Running layout effect setting code * Running effect setting code

For more information, see Working Group posts atAdded reusable state to StrictModeEUHow to support reusable state in Effects.

Setting up the test environment

When you first update your tests for usecriarRoot, in the test console you can see this warning:

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

To fix this, setglobalThis.IS_REACT_ACT_ENVIRONMENTTo doTRUEbefore running the test:

// In your test config fileglobalTo.IS_REACT_ACT_ENVIRONMENT = TRUE;

The purpose of the flag is to let React know it's running in a unit test environment. React will log helpful warnings if you forget to include an updateto work.

You can also set the flag toFALSEHOODsay reactto workit is not necessary. This can be useful for end-to-end tests that simulate a full browser environment.

Hopefully eventually the test libraries will automatically configure this. For examplenext version of React Testing Library has built-in support for React 18without additional configuration.

More backgrounds into workAPI testing and related changesis available in the workgroup.

(Video) The Plan for react 18 | Explained

End of support for Internet Explorer

In this release, React drops support for Internet Explorer, i.e.exit support on June 15, 2022. We are making this change now because the new features introduced in React 18 are built using modern browser features such as microtasks that cannot be completed correctly in IE.

If you need support for Internet Explorer, we recommend sticking with React 17.


  • to react:ReactDOM.renderhas been deprecated. Using it will prompt you and run your app in React 17 mode.
  • to react:ReactDOM.hydratehas been deprecated. Using it will prompt you and run your app in React 17 mode.
  • to react:ReactDOM.unmountComponentAtNodehas been deprecated.
  • to react:ReactDOM.renderSubtreeIntoContainerhas been deprecated.
  • react-home/servidor:ReactDOMServer.renderToNodeStreamhas been deprecated.

Other innovative changes

  • Consistent use Effect time: React now always releases effect functions synchronously if an update was triggered during a discrete user input event, such as a click or keypress event. Previously, behavior was not always predictable or consistent.
  • More stringent hydration errors: Hydration mismatches caused by missing or extra text content are now treated as errors instead of warnings. React will no longer attempt to "fix" individual nodes by inserting or deleting a node on the client to match the server's tags and will revert to rendering the client to the nearest<Uncertainty>tree edge. This ensures the consistency of the watered tree and avoids potential privacy and security gaps that can be caused by hydration mismatch.
  • Hanging trees are always consistent:If a component crashes before being fully added to the tree, React will not add it to the tree in an incomplete state or run its effects. Instead, React will completely dump the new tree, wait for the async operation to complete, and try to render from scratch again. React will retry simultaneously and without blocking the browser.
  • Dropdown layout effects: When the tree crashes again and goes back to a crashed state, React will now clear the layout effects and recreate them when the content inside the border is redisplayed. This fixes an issue that prevented component libraries from correctly measuring layout when used with suspense.
  • New JS environment requirements: React now depends on the capabilities of modern browsers, incl.Promise,Symbol, EUobject.assign. If you support older browsers and devices, such as Internet Explorer, that don't natively support modern browser features or have incompatible implementations, consider enabling global polygon filling in your integrated app.

Other Significant Changes

to react

  • Components can now renderindeterminate:React no longer warns you if you returnindeterminateof the component. This ensures that the allowed values ​​returned by the components match the allowed values ​​in the center of the component tree. We suggest using a linter to avoid errors like forgettingturn backstatement before JSX.
  • you test meto workwarnings are now optional:If you run comprehensive tests,to workwarnings are unnecessary. we introducedconsentmechanism so that they can only be included in unit tests where they are useful and beneficial.
  • No notice aboutdefine stateon disassembled components:Previously, React warned about memory leaks when callingdefine stateon a disassembled component. This warning was added to the signature, but people mostly encounter it in scenarios where the state setting is fine and the workarounds make the code worse. usREMOVEDit's a warning.
  • Without ignoring console logs:When you use strict mode, React renders each component twice to help you find unexpected side effects. In React 17, we disabled console logs for one of the two renders to make it easier to read. In reply tocommunity feedbackbecause it is confusing, we remove the lock. Instead, if you have React DevTools installed, the second log rendering will be grayed out and there will be an option (off by default) to hide it completely.
  • Improved memory usage:React now cleans up more internal fields when unmounting, making the impact of unpatched memory leaks that can occur in application code less severe.

React DOM server

  • renderToString:There will no longer be an error when crashing on the server. Instead, it will output the placeholder HTML to the closest<Uncertainty>border and try to re-render the same content on the client. It is still recommended to switch to a streaming API likerendering to a pipeline streamlubricantrendering to a readable streamInstead of.
  • renderToStaticMarkup:There will no longer be an error when crashing on the server. Instead, it will output the placeholder HTML to the closest<Uncertainty>border.

a list of changes

you can watchfull list of changes here.


1. Setup React 18 with TypeScript
2. How to upgrade to React 18 | React 17 to 18 | What's new in React 18? | AnaghTech | #React18
(Anagh Technologies Inc.)
3. React 18 useTransition Hook Crash Course
(Web Dev Simplified)
4. React v18.0 | What is new in React version 18 | How to Install Update and run React JS v18
(Norbert BM Web Development)
5. Adding functionality to your React blog components (Part 3/4) - Build your first blog using React
(Sanity Composable Content Cloud)
6. CIS658 - React 18 Upgrade Woes!
(Erik Fredericks)
Top Articles
Latest Posts
Article information

Author: Wyatt Volkman LLD

Last Updated: 03/26/2023

Views: 5510

Rating: 4.6 / 5 (46 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Wyatt Volkman LLD

Birthday: 1992-02-16

Address: Suite 851 78549 Lubowitz Well, Wardside, TX 98080-8615

Phone: +67618977178100

Job: Manufacturing Director

Hobby: Running, Mountaineering, Inline skating, Writing, Baton twirling, Computer programming, Stone skipping

Introduction: My name is Wyatt Volkman LLD, I am a handsome, rich, comfortable, lively, zealous, graceful, gifted person who loves writing and wants to share my knowledge and understanding with you.