Movatterモバイル変換


[0]ホーム

URL:


Is this page useful?

createRoot lets you create a root to display React components inside a browser DOM node.

constroot =createRoot(domNode,options?)

Reference

createRoot(domNode, options?)

CallcreateRoot to create a React root for displaying content inside a browser DOM element.

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

constdomNode =document.getElementById('root');
constroot =createRoot(domNode);

React will create a root for thedomNode, and take over managing the DOM inside it. After you’ve created a root, you need to callroot.render to display a React component inside of it:

root.render(<App/>);

An app fully built with React will usually only have onecreateRoot 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.

See more examples below.

Parameters

  • domNode: ADOM element. React will create a root for this DOM element and allow you to call functions on the root, such asrender to display rendered React content.

  • optionaloptions: An object with options for this React root.

    • optionalonCaughtError: Callback called when React catches an error in an Error Boundary. Called with theerror caught by the Error Boundary, and anerrorInfo object containing thecomponentStack.
    • optionalonUncaughtError: Callback called when an error is thrown and not caught by an Error Boundary. Called with theerror that was thrown, and anerrorInfo object containing thecomponentStack.
    • optionalonRecoverableError: Callback called when React automatically recovers from errors. Called with anerror React throws, and anerrorInfo object containing thecomponentStack. Some recoverable errors may include the original error cause aserror.cause.
    • optionalidentifierPrefix: 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 andunmount.

Caveats

  • If your app is server-rendered, usingcreateRoot() is not supported. UsehydrateRoot() instead.
  • You’ll likely have only onecreateRoot call 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), usecreatePortal instead ofcreateRoot.

root.render(reactNode)

Callroot.render to display a piece ofJSX (“React node”) into the React root’s browser DOM node.

root.render(<App/>);

React will display<App /> in theroot, and take over managing the DOM inside it.

See more examples below.

Parameters

  • reactNode: AReact 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 returnsundefined.

Caveats

  • The first time you callroot.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, usehydrateRoot() instead, which attaches the event handlers to the existing HTML.

  • If you callrender on 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. Callingrender on the same root again is similar to calling theset function 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(...) influshSync to ensure the initial render runs fully synchronously.

    constroot =createRoot(document.getElementById('root'));
    root.render(<App/>);
    // 🚩 The HTML will not include the rendered <App /> yet:
    console.log(document.body.innerHTML);

root.unmount()

Callroot.unmount to destroy a rendered tree inside a React root.

root.unmount();

An app fully built with React will usually not have any calls toroot.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 callingroot.unmount. Otherwise, the components inside the removed root won’t know to clean up and free up global resources like subscriptions.

Callingroot.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 returnsundefined.

Caveats

  • Callingroot.unmount will unmount all the components in the tree and “detach” React from the root DOM node.

  • Once you callroot.unmount you cannot callroot.render again on the same root. Attempting to callroot.render on 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.

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

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

Usually, you only need to run this code once at startup. It will:

  1. Find thebrowser DOM node defined in your HTML.
  2. Display theReact component for your app inside.
Fork
import{createRoot}from'react-dom/client';importAppfrom'./App.js';import'./styles.css';constroot =createRoot(document.getElementById('root'));root.render(<App/>);

If your app is fully built with React, you shouldn’t need to create any more roots, or to callroot.render again.

From this point on, React will manage the DOM of your entire app. To add more components,nest them inside theApp component. When you need to update the UI, each of your components can do this byusing 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:

<divid="root"></div>

This can feel very slow! To solve this, you can generate the initial HTML from your componentson 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 recommendusing a framework that does this optimization out of the box. Depending on when it runs, this is calledserver-side rendering (SSR) orstatic site generation (SSG).

Pitfall

Apps using server rendering or static generation must callhydrateRoot instead ofcreateRoot. React will thenhydrate (reuse) the DOM nodes from your HTML instead of destroying and re-creating them.


Rendering a page partially built with React

If your pageisn’t fully built with React, you can callcreateRoot 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 callingroot.render.

Here, two different React components are rendered into two DOM nodes defined in theindex.html file:

Fork
import'./styles.css';import{createRoot}from'react-dom/client';import{Comments,Navigation}from'./Components.js';constnavDomNode =document.getElementById('navigation');constnavRoot =createRoot(navDomNode);navRoot.render(<Navigation/>);constcommentDomNode =document.getElementById('comments');constcommentRoot =createRoot(commentDomNode);commentRoot.render(<Comments/>);

You could also create a new DOM node withdocument.createElement() and add it to the document manually.

constdomNode =document.createElement('div');
constroot =createRoot(domNode);
root.render(<Comment/>);
document.body.appendChild(domNode);// You can add it anywhere in the document

To remove the React tree from the DOM node and clean up all the resources used by it, callroot.unmount.

root.unmount();

This is mostly useful if your React components are inside an app written in a different framework.


Updating a root component

You can callrender more than once on the same root. As long as the component tree structure matches up with what was previously rendered, React willpreserve the state. Notice how you can type in the input, which means that the updates from repeatedrender calls every second in this example are not destructive:

Fork
import{createRoot}from'react-dom/client';import'./styles.css';importAppfrom'./App.js';constroot =createRoot(document.getElementById('root'));leti =0;setInterval(()=>{root.render(<Appcounter={i}/>);i++;},1000);

It is uncommon to callrender multiple times. Usually, your components willupdate state instead.

Error logging in production

By default, React will log all errors to the console. To implement your own error reporting, you can provide the optional error handler root optionsonUncaughtError,onCaughtError andonRecoverableError:

import{createRoot}from"react-dom/client";
import{reportCaughtError}from"./reportError";

constcontainer =document.getElementById("root");
constroot =createRoot(container,{
onCaughtError:(error,errorInfo)=>{
if(error.message !=="Known error"){
reportCaughtError({
error,
componentStack:errorInfo.componentStack,
});
}
},
});

TheonCaughtError option is a function called with two arguments:

  1. Theerror that was thrown.
  2. AnerrorInfo object that contains thecomponentStack of the error.

Together withonUncaughtError andonRecoverableError, you can can implement your own error reporting system:

Fork
import{createRoot}from"react-dom/client";importAppfrom"./App.js";import{onCaughtErrorProd,onRecoverableErrorProd,onUncaughtErrorProd,}from"./reportError";constcontainer =document.getElementById("root");constroot =createRoot(container,{// Keep in mind to remove these options in development to leverage// React's default handlers or implement your own overlay for development.// The handlers are only specfied unconditionally here for demonstration purposes.onCaughtError:onCaughtErrorProd,onRecoverableError:onRecoverableErrorProd,onUncaughtError:onUncaughtErrorProd,});root.render(<App/>);

Troubleshooting

I’ve created a root, but nothing is displayed

Make sure you haven’t forgotten to actuallyrender your app into the root:

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

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

Until you do that, nothing is displayed.


I’m getting an error: “You passed a second argument to root.render”

A common mistake is to pass the options forcreateRoot toroot.render(...):

Console
Warning: You passed a second argument to root.render(…) but it only accepts one argument.

To fix, pass the root options tocreateRoot(...), notroot.render(...):

// 🚩 Wrong: root.render only takes one argument.
root.render(App,{onUncaughtError});

// ✅ Correct: pass options to createRoot.
constroot =createRoot(container,{onUncaughtError});
root.render(<App/>);

I’m getting an error: “Target container is not a DOM element”

This error means that whatever you’re passing tocreateRoot is not a DOM node.

If you’re not sure what’s happening, try logging it:

constdomNode =document.getElementById('root');
console.log(domNode);// ???
constroot =createRoot(domNode);
root.render(<App/>);

For example, ifdomNode isnull, it means thatgetElementById returnednull. This will happen if there is no node in the document with the given ID at the time of your call. There may be a few reasons for it:

  1. The ID you’re looking for might differ from the ID you used in the HTML file. Check for typos!
  2. Your bundle’s<script> tag cannot “see” any DOM nodes that appearafter it in the HTML.

Another common way to get this error is to writecreateRoot(<App />) instead ofcreateRoot(domNode).


I’m getting an error: “Functions are not valid as a React child.”

This error means that whatever you’re passing toroot.render is not a React component.

This may happen if you callroot.render withComponent instead of<Component />:

// 🚩 Wrong: App is a function, not a Component.
root.render(App);

// ✅ Correct: <App /> is a component.
root.render(<App/>);

Or if you pass a function toroot.render, instead of the result of calling it:

// 🚩 Wrong: createApp is a function, not a component.
root.render(createApp);

// ✅ Correct: call createApp to return a component.
root.render(createApp());

My server-rendered HTML gets re-created from scratch

If your app is server-rendered and includes the initial HTML generated by React, you might notice that creating a root and callingroot.render deletes all that HTML, and then re-creates all the DOM nodes from scratch. This can be slower, resets focus and scroll positions, and may lose other user input.

Server-rendered apps must usehydrateRoot instead ofcreateRoot:

import{hydrateRoot}from'react-dom/client';
importAppfrom'./App.js';

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

Note that its API is different. In particular, usually there will be no furtherroot.render call.



[8]ページ先頭

©2009-2025 Movatter.jp