Major Change of Root API in React 18-Alpha latest release

Major Change of Root API in React 18-Alpha latest release

463Reads
16 March, 2022

Recently React 18-Alpha was released and here is all you need to know about the change in Root API in brief.

The render function, which is called at the start of every React project, will be replaced with createRoot for some user-facing API capabilities.

The new API serves as a portal to the new React 18 capabilities. It's included with the legacy API to facilitate the gradual transition and eliminate performance comparisons. The syntax of the new Root API is also a little different.

import ReactDOM from "react-dom";

import App from "App";

const container = document.getElementById("app");

// Old

ReactDOM.render(<App />, container);

// New

const root = ReactDOM.createRoot(container);

root.render(<App />);

Take note of how your React app's root is now separated. The top-level data structure pointer attached to a DOM element, known as Root, was previously invisible to the render function user.

You must first use the createRoot function to create the root, and then call the render method on it. This not only allows for additional functionality but also makes it clearer and easier to update as needed.

The render callback and hydrate functions are also affected by the new API. Due to difficulty in properly timing the callback argument, it has been eliminated entirely. Instead, use a timeout or ref callback on the root, for example.

// Old

ReactDOM.render(<App />, container, () => console.log("renderered"));

// New

const App = ({ callback }) => {

return (

<div ref={callback}>

{"Hi"}

</div>

);

}

const root = ReactDOM.createRoot(container);

root.render(<App callback={() => console.log("renderered")} />);

A hydrate is now a config option rather than a distinct function, making it more useful. A related WG threadcan be found here.

// Old

ReactDOM.hydrate(<App />, container);

// New

const root = ReactDOM.createRoot(container, { hydrate: true });

root.render(<App />);