ReactDOM.render deprecated in React 18

It's been a while since I looked at using the React library but I recently discovered some issues with some code written a while a go and recently compiled
In React 18,
render
was replaced bycreateRoot
. Usingrender
in React 18 will warn that your app will behave as if it’s running React 17. Learn more here.
If you are using an earlier version of react this, render was the default method for rendering your JSX or react components.
Instead of
import { render } from 'react-dom';
We can use
import { createRoot } from 'react-dom/client';
and instead of
render(<App/>, document.querySelector('#my-app-root'))
we can define the root like so:
const domNode = document.getElementById('my-app-root');
const root = createRoot(domNode);
and then render like so:
root.render(
<App />
);
It is also best practice to wrap our component using the strictmode component that should only run in development environments (not production) this is useful tool to help identify any issues with your code.. e.g.
import { StrictMode } from 'react';
and
root.render(
<StrictMode>
<App />
</StrictMode>
);
This is a potentially breaking change when running later versions of React. So why have they changed it? Well it turns out there is a benefit:
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.
// 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" />);
https://18.react.dev/blog/2022/03/08/react-18-upgrade-guide#updates-to-client-rendering-apis
More on the reasons for this change here:
What are the differences?
There are a few reasons we changed the API.
First, this fixes some of the ergonomics of the API when running updates. As shown above, in the legacy API, you need to continue to pass the container into render, even though it never changes. This also mean that we don’t need to store the root on the DOM node, though we still do that today.
Second, this change allows us to remove the
hydrate
method and replace with with an option on the root; and remove the render callback, which does not make sense in a world with partial hydration.
Add new comment