The biggest change in React 18 is the addition of concurrent rendering. With concurrent rendering, you can mark state updates as non-urgent in order to improve the performance of your user interface.
Concurrent rendering is opt-in. What this means is that it’s only enabled when you use a concurrent feature. As a result, apps built with previous versions of React (and every listing in my book) will work with React 18 with no changes.
If you want to start learning to use new concurrent features in React, you’ll need to make a couple changes to the file that renders your root component to replace ReactDOM.render()
with ReactDOM.createRoot().render()
.
Here’s an example of a typical index.js file in a React 17 app.
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
const root = document.getElementById('root');
ReactDOM.render(<App />, root);
This code will still work in React 18 with no changes. If you want to use new features of React 18, you’ll need to upgrade it. The steps to upgrade to React 18 are as follows:
- Open package.json and find the dependencies array. Change the versions for react and react-dom to the following:
"react": "^18.0.0",
"react-dom": "^18.0.0", - Open a terminal window and navigate to the root of your project and enter the following:
npm install - Open the file that calls ReactDOM.render (it’s probably index.js) and add /client to the path you’re importing it from. So, if you had:
import ReactDOM from 'react-dom/';
it will now be
import ReactDOM from 'react-dom/client'; - Change ReactDOM.render to ReactDOM.createRoot.render. Basically, instead of passing two parameters to ReactDOM.render, you’re now going to pass only the root component to the render method, and the location where you want to render it to the createRoot method.
So, if you previously had this:
ReactDOM.render(<App />, root);
You’ll now have this:
ReactDOM.createRoot(root).render(<App />);
Your final, upgraded, index.js should look like this:
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
const root = document.getElementById('root');
ReactDOM.createRoot(root).render(<App />);
Run your app and make sure everything still works. Congratulations!
In the coming weeks, I’ll post additional updates explaining how to use the new features of React 18.