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

16 March, 2022
411 read  ·  2 Hearts
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(, container);

// New
const root = ReactDOM.createRoot(container);

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(, container, () => console.log("renderered"));

// New
const App = ({ callback }) => {
  return (
); } const root = ReactDOM.createRoot(container); root.render( console.log("renderered")} />);

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

// Old
ReactDOM.hydrate(, container);

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

Engineering React React Developer React 18 javascript JavaScript frameworks developer Software Developer web devlopment
Comments  ·  0
You need to be Logged in to Comment. Login

More from @algosource


Need Help? ·  About
Terms and Conditions ·  Contact ·  Privacy

© 2021 ayedot. All Rights Reserved.