Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between createRoot and ReactDOM.render

What is the difference between ReactDOM.render and createRoot which is introduced in React18?

like image 660
Kartik Kh Avatar asked Jun 23 '26 07:06

Kartik Kh


2 Answers

When rendering a React component to the DOM, the methods createRoot and ReactDOM.render are both used, but they differ in a few ways.

The conventional technique for rendering a React component to a particular DOM element—typically the root of your app—is ReactDOM.render. Consider this:

ReactDOM.render(<App />, document.getElementById('root'));

In this instance, the <App/> component is being rendered to the <div id="root"></div> element on the page.

createRoot : In order to render components in a new way with better performance and better support for concurrent mode, React 17 introduced a new method called createRoot. The fundamental operation of createRoot is similar to that of ReactDOM.render, except that it creates a new root container and returns a reference to it rather than rendering to a particular DOM node. Then, you can render your components to the root container using the returned reference. For instance:

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

In conclusion, the primary distinction between createRoot and ReactDOM.render is that createRoot generates a new root container for rendering components, whereas ReactDOM.render renders components directly to a given DOM element.

like image 101
Hassan Ali Avatar answered Jun 24 '26 20:06

Hassan Ali


With createRoot and the associated root.render function, you can run multiple calls to render using the same container DOM element, unlike ReactDOM.render, in which every call to render requires a new call to the Document API. You can avoid multiple searches of the DOM by storing the root element in a variable, but the new root API with createRoot maximizes readability. There are a few other differences, which you can see at https://thelonecoder.dev/javascript/react-js/reactdom-render-vs-createroot/

To use the new root API with createRoot, change the legacy root code in your index.js to the following:

import { createRoot } from 'react-dom/client';
import App from './App';

const root = createRoot(document.getElementById('root'));
root.render(<App />);
like image 27
christian_js Avatar answered Jun 24 '26 19:06

christian_js



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!