createRoot
createRoot lets you create a root to display React components inside a browser DOM node.
const root = createRoot(domNode, options?)
Reference
createRoot(domNode, options?)
Call createRoot to create a React root for displaying content inside a browser DOM element.
import { createRoot } from 'react-dom/client';
const domNode = document.getElementById('root');
const root = createRoot(domNode);
React will create a root for the domNode, and take over managing the DOM inside it. After you've created a root, you need to call root.render to display a React component inside of it:
root.render(<App />);
An app fully built with React will usually only have one createRoot call for its root component. A page that uses "sprinkles" of React for parts of the page may have as many separate roots as needed.
Parameters
-
domNode: A DOM element. React will create a root for this DOM element and allow you to call functions on the root, such asrenderto display rendered React content. -
optional
options: An object with options for this React root. -
optional
onCaughtError: Callback called when React catches an error in an Error Boundary. Called with theerrorcaught by the Error Boundary, and anerrorInfoobject containing thecomponentStack. - optional
onUncaughtError: Callback called when an error is thrown and not caught by an Error Boundary. Called with theerrorthat was thrown, and anerrorInfoobject containing thecomponentStack. - optional
onRecoverableError: Callback called when React automatically recovers from errors. Called with anerrorReact throws, and anerrorInfoobject containing thecomponentStack. Some recoverable errors may include the original error cause aserror.cause. - optional
identifierPrefix: A string prefix React uses for IDs generated byuseId. Useful to avoid conflicts when using multiple roots on the same page.
Returns
createRoot returns an object with two methods: render and unmount.
Caveats
- If your app is server-rendered, using
createRoot()is not supported. UsehydrateRoot()instead. - You'll likely have only one
createRootcall in your app. If you use a framework, it might do this call for you. - When you want to render a piece of JSX in a different part of the DOM tree that isn't a child of your component (for example, a modal or a tooltip), use
createPortalinstead ofcreateRoot.
root.render(reactNode)
Call root.render to display a piece of JSX ("React node") into the React root's browser DOM node.
root.render(<App />);
React will display <App /> in the root, and take over managing the DOM inside it.
Parameters
reactNode: A React node that you want to display. This will usually be a piece of JSX like<App />, but you can also pass a React element constructed withcreateElement(), a string, a number,null, orundefined.
Returns
root.render returns undefined.
Caveats
-
The first time you call
root.render, React will clear all the existing HTML content inside the React root before rendering the React component into it. -
If your root's DOM node contains HTML generated by React on the server or during the build, use
hydrateRoot()instead, which attaches the event handlers to the existing HTML. -
If you call
renderon the same root more than once, React will update the DOM as necessary to reflect the latest JSX you passed. React will decide which parts of the DOM can be reused and which need to be recreated by "matching it up" with the previously rendered tree. Callingrenderon the same root again is similar to calling thesetfunction on the root component: React avoids unnecessary DOM updates. -
Although rendering is synchronous once it starts,
root.render(...)is not. This means code afterroot.render()may run before any effects (useLayoutEffect,useEffect) of that specific render are fired. This is usually fine and rarely needs adjustment. In rare cases where effect timing matters, you can wraproot.render(...)influshSyncto ensure the initial render runs fully synchronously.
const root = createRoot(document.getElementById('root'));
root.render(<App />);
// 🚩 The HTML will not include the rendered <App /> yet:
console.log(document.body.innerHTML);
```
---
### `root.unmount()`
Call `root.unmount` to destroy a rendered tree inside a React root.
```js
root.unmount();
An app fully built with React will usually not have any calls to root.unmount.
This is mostly useful if your React root's DOM node (or any of its ancestors) may get removed from the DOM by some other code. For example, imagine a jQuery tab panel that removes inactive tabs from the DOM. If a tab gets removed, everything inside it (including the React roots inside) would get removed from the DOM as well. In that case, you need to tell React to "stop" managing the removed root's content by calling root.unmount. Otherwise, the components inside the removed root won't know to clean up and free up global resources like subscriptions.
Calling root.unmount will unmount all the components in the root and "detach" React from the root DOM node, including removing any event handlers or state in the tree.
Parameters
root.unmount does not accept any parameters.
Returns
root.unmount returns undefined.
Caveats
-
Calling
root.unmountwill unmount all the components in the tree and "detach" React from the root DOM node. -
Once you call
root.unmountyou cannot callroot.renderagain on the same root. Attempting to callroot.renderon an unmounted root will throw a "Cannot update an unmounted root" error. However, you can create a new root for the same DOM node after the previous root for that node has been unmounted.
Usage
Rendering an app fully built with React
If your app is fully built with React, create a single root for your entire app.
```js [[1, 3, "document.getElementById('root')"], [2, 4, "
const root = createRoot(document.getElementById('root'));
root.render(
Usually, you only need to run this code once at startup. It will:
1. Find the <CodeStep step={1}>browser DOM node</CodeStep> defined in your HTML.
2. Display the <CodeStep step={2}>React component</CodeStep> for your app inside.
```html public/index.html
<!DOCTYPE html>
<html>
<head><title>My app</title></head>
<body>
<!-- This is the DOM node -->
<div id="root"></div>
</body>
</html>
```js src/index.js active import { createRoot } from 'react-dom/client'; import App from './App.js'; import './styles.css';
const root = createRoot(document.getElementById('root'));
root.render(
```js src/App.js
import { useState } from 'react';
export default function App() {
return (
<>
<h1>Hello, world!</h1>
<Counter />
</>
);
}
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
You clicked me {count} times
</button>
);
}
If your app is fully built with React, you shouldn't need to create any more roots, or to call root.render again.
From this point on, React will manage the DOM of your entire app. To add more components, nest them inside the App component. When you need to update the UI, each of your components can do this by using state. When you need to display extra content like a modal or a tooltip outside the DOM node, render it with a portal.
[!NOTE]
When your HTML is empty, the user sees a blank page until the app's JavaScript code loads and runs:
<div id="root"></div>
This can feel very slow! To solve this, you can generate the initial HTML from your components on the server or during the build. Then your visitors can read text, see images, and click links before any of the JavaScript code loads. We recommend using a framework that does this optimization out of the box. Depending on when it runs, this is called server-side rendering (SSR) or static site generation (SSG).
[!WARNING]
Apps using server rendering or static generation must call
hydrateRootinstead ofcreateRoot. React will then hydrate (reuse) the DOM nodes from your HTML instead of destroying and re-creating them.
Rendering a page partially built with React
If your page isn't fully built with React, you can call createRoot multiple times to create a root for each top-level piece of UI managed by React. You can display different content in each root by calling root.render.
Here, two different React components are rendered into two DOM nodes defined in the index.html file:
```html public/index.html
This paragraph is not rendered by React (open index.html to verify).
```
