How to Upgrade to React 18?
Last Updated :
27 May, 2024
React 18 evolves the popular JavaScript component framework with new features built around concurrent rendering and suspense. It promises better performance, more capabilities, and an improved developer experience for apps that make the switch.
In this article, we'll guide you through the steps to upgrade to React 18. Along with this, we will also showcase some of the features that are introduced in React 18.
Installing React 18
With Create React App Command
Step 1: Create the React Project using CRA command
npx create-react-app myapp
Step 2: Move to the project directory
cd myapp
Step 3: Install React 18 as a dependency with the following command
npm i react@18 react-dom@18
The updated dependencies in package.json file:
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
Using NPM or Yarn
Step 1: To install the latest version, from your project folder run the following from the terminal:
For npm:
npm i react@18 react-dom@18
For yarn:
yarn add react@18 react-dom@18
Step 2: Update to Client Rendering APIs.
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 the concurrent features.
Before:
import { render } from 'react-dom' ;
const container = document.getElementById('app') ;
render(<App tab="home" />, container) ;
After:
import { createRoot } from 'react-dom/client';
const container = document.getElementById('app');
const root = createRoot(container); // createRoot(container!) if you use TypeScript
root.render(<App tab="home" />);
Note: Your application will work without using the root API. If you continue to use ReactDom.render your application will behave like React 17.
Some updates of React 18
1. React changed unmountComponentAtNode to root.unmount :
Before:
unmountComponentAtNode(container);
After:
root.unmount();
2. React removed the callback from render:
Before:
const container = document.getElementById('app');
render(<App tab="home" />, container, () => {
console.log('rendered');
});
After:
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.
3. Upgraded hydrate to hydrateRoot :
Before:
import { hydrate } from 'react-dom';
const container = document.getElementById('app');
hydrate(<App tab="home" />, container);
After:
import { hydrateRoot } from 'react-dom/client';
const container = document.getElementById('app');
const root = hydrateRoot(container, <App tab="home" />);
// Unlike with createRoot, you don't need a separate root.render() call here.
4. Dropping support for IE:-
React 18's new features are developed with contemporary browser capabilities like microtasks, which Internet Explorer is unable to polyfill well enough. React 18 officially drops support for Internet Explorer (IE) due to its low usage and security vulnerabilities. This means that IE users will no longer receive official compatibility updates or bug fixes for React applications.
Impact: If your application targets IE users, you'll need to consider alternative strategies, such as:
- Providing a legacy version of your application specifically for IE users.
- Migrating existing IE users to compatible browsers.
- Exploring polyfills or transpilers to bridge some compatibility gaps, but be aware of potential limitations and maintenance overhead.
5. Updates to Server Rendering APIs
React 18 introduces new server rendering APIs to enable streaming capabilities and improve performance:
- renderToReadableStream: Allows streaming rendering, where the server can send HTML chunks to the browser progressively, instead of waiting for the entire content to be generated. This can improve perceived performance for users.
- hydrateRoot: This API is used for hydrating server-rendered content on the client-side. It ensures seamless switching between server-rendered content and interactive client-side rendering.
Impact: If you're using server-side rendering (SSR) in your React application:
- Update your SSR code to use renderToReadableStream for streaming if desired.
- Replace any uses of renderToNodeStream with hydrateRoot.
6. Updates to Client Rendering APIs
The primary change in client rendering involves the new createRoot API:
- It replaces the older ReactDOM.render API in React 18.
- This API is used to create a "root" element where your React application will be rendered.
Impact: Update your client-side code to use createRoot instead of ReactDOM.render.
The basic structure remains similar:
JavaScript
// After React 18
import { createRoot } from 'react-dom/client';
const root = createRoot(document.getElementById('root'));
root.render(<App />);
// Before React 18
ReactDOM.render(<App />, document.getElementById('root'));
7. Deprecations
React 18 deprecates a few APIs or behaviors that are considered outdated or less optimal:
- Legacy Context API: The older context API using createLegacyContext is deprecated in favor of the more flexible createContext introduced in React 16.8.
- findDOMNode: This method is discouraged as it can lead to unintended side effects and tight coupling between React components and DOM manipulation. Consider alternative approaches like refs or event delegation.
- SyntheticEvent.nativeEvent: This property provides access to the underlying browser event object, but its use is generally discouraged as it tightly couples React to browser-specific event details. Prefer React's synthetic events system for better abstraction.
Impact: If you're using any of these deprecated APIs, update your code to use the recommended alternatives to ensure compatibility and maintainability.
Major Changes in React 18:
Beyond the specific API updates and deprecations, React 18 introduces some significant architectural changes:
- Concurrent Mode: This new mode enables React to render multiple components concurrently, potentially improving performance and responsiveness in certain scenarios. However, it requires careful consideration and potential code adjustments to ensure your application works as expected in concurrent mode.
- Automatic Batching: React 18 automatically batches state updates for better performance. While this behavior is generally beneficial, it's important to be aware of its implications for managing state updates, especially in event handlers or asynchronous operations.
Impact: Thoroughly test your application after upgrading to React 18, paying close attention to any potential behavior changes related to concurrent rendering and automatic batching. Consider using the React DevTools profiling features to identify any performance bottlenecks or unexpected behavior.
Changes to React DOM Server in React 18:
React 18 separates the React DOM library into two parts: react-dom for client-side rendering and react-dom/server for server-side rendering.
Impact: If you're using server-side rendering, import react-dom/server explicitly where needed in your server-side code.
Similar Reads
How to Set Up a Vite Project?
Vite is a modern front-end build tool that offers a fast development experience by using native ES modules in the browser. It provides a lean and efficient setup for building JavaScript applications with a focus on performance and simplicity. PrerequisitesNodejsReactJavaScript Approach We have discu
2 min read
How to add theme to your React App?
Themes play a crucial role in web applications, ensuring a cohesive visual identity. They serve to regulate and define various aspects such as color schemes, backgrounds, font properties, shadow levels, opacity, and more, thereby maintaining a consistent and harmonized aesthetic throughout the appli
4 min read
How to use styles in ReactJS ?
React is a popular JavaScript library for building single-page applications (SPAs) with dynamic user interfaces. Styling in React can be done in various ways, each with its advantages. In this article, we will explore different approaches to applying styles in React, including inline styles, CSS fil
4 min read
How to Update Parent State in ReactJS ?
Updating the parent state in React involves passing a callback function as a prop to the child that triggers the state change and updates the data in the state.Prerequisites:ReactJSReact State and PropsReact Components ApproachTo update parent state in React we will pass a function as a prop to the
3 min read
How to use TypeScript with React?
TypeScript enhances JavaScript by adding strict type definitions, making your code more robust and maintainable. ReactJS, a popular library for building user interfaces, pairs excellently with TypeScript to create clean, efficient, and scalable codebases. Combining TypeScript with React offers a pow
3 min read
How React and ReactDOM works?
When you work with React, it is more than likely that you will build your apps with JSX. The JSX is a tag-based JavaScript syntax like looks familiar with HTML. React element is the atomic and most basic unit that you need to master before JSX and before moving forward with React. Note: In order to
9 min read
How React Works?
React is a tool made by Facebook to help create user interfaces, especially for single-page applications where the interface changes often and data updates a lot. It lets developers build reusable pieces of the interface, each managing its own state, which makes apps more efficient and simpler to ma
10 min read
How to Migrate npm to yarn?
JavaScript is a programming language that is popular among programmers, yarn is a package manager for JavaScript that can also help to install modules on Node.js besides npm (Node Package Manager). Node.js comes bundled with npm installed by default and still, you can also use yarn to manage one's p
2 min read
How to setup ReactJs with Vite ?
Vite is a fast and modern build tool for creating web applications. It increases the development process by providing faster build times and better performance. Some of the benefits of using React with Vite are mentioned below:Fast updates without page reloads.Faster and smaller production builds.Au
3 min read
How to setup React Router v6 ?
React Router is an amazing library that was created by Remix. The purpose of React Router is to enable Client-Side routing in the React application, that is, by using React Router we can create different routes in our React app and can easily navigate to different pages without even reloading the pa
6 min read