React 17 released in August 2020, didn’t bring new features but built a foundation for seamless adoption of future updates. The React team has recently announced the plan for React 18 and published React 18 Alpha to give it a try and provide feedback.
One of the most important changes in React 18 is
the introduction of the new root API (
Before going into the details of the new API, let’s check out the existing root API.
The Root API
In React, we render our App component into the root element on the page. Here we are using a simple example similar to the one used in the original discussion.
This root API (now called “legacy root API”) has some issues when running updates.
We need to continue passing the
container into the render, even though it never changes.
To fix this issue and bring some improvements, React 18 introduced a new root API.
The New Root API
The addition of the new root API fixes the issue of passing
the container while running the updates.
We no longer need to pass the
container into the render.
What happens to render callback and hydrate functions?
The new root API happens to be the gateway for accessing new features of React 18 and adds out-of-the-box improvements.
It also changes the way render callback and hydrate function work.
In the legacy root API, we could pass a callback to render which would get called after the component is rendered or updated.
The callback argument is completely removed in the new root API
due to difficulties in timing it properly.
It is recommended to use
setTimeout, or a
ref callback on the root.
is similar to
It is used to hydrate
a container whose HTML contents were rendered by
React preserves the markup and only attaches event handlers, giving a performant first-load experience.
Let’s check out the changes of hydrate before and after the new root API.
hydrate in the legacy root API -
In the new root API,
hydrate is moved to
as below -
React 18 ships the new root API (
ReactDOM.createRoot ) together with the legacy API (
ReactDOM.render) for encouraging gradual adoption and ease-out performance comparisons.
If we have installed the React 18 Alpha version and did not update the new root API, the app will not support the features present in React 18.
It will give the below warning -
For deeper dive into the new root API, check out this WG thread.