Sub topic 3
Opting in with createRoot
This chapter assumes you can write React function components, use useState, and have a project already running on React 18 or later. It covers the one change that makes transitions and deferred values work: how you mount the app.
Why the root API matters
The features in this tutorial are startTransition, useTransition and useDeferredValue. They all rely on concurrent rendering, where React can pause a render, handle a more urgent update, and then resume or discard the paused work.
React does not enable this behavior globally. It is tied to the way you create the root of your app. The root is the object that connects a DOM container, such as <div id="root">, to your component tree.
React 18 ships two root APIs:
- Legacy root.
ReactDOM.renderfromreact-dom. It keeps the React 17 behavior: every render runs to completion without interruption. - Concurrent root.
createRootfromreact-dom/client. It enables concurrent rendering, so React can interrupt non-urgent renders.
If you upgrade the react package but leave ReactDOM.render in place, your app keeps working as before. The new hooks also exist and do not throw. They just give you nothing, because there is no interruptible rendering underneath them.
The minimal change
This is the React 17 style of mounting:
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));This is the React 18 and later style:
import { createRoot } from 'react-dom/client';
import App from './App';
const container = document.getElementById('root');
const root = createRoot(container);
root.render(<App />);Three details are worth noting.
- The import comes from
react-dom/client, notreact-dom. - Creating the root and rendering are separate steps. You keep the
rootobject so you can callroot.renderagain orroot.unmount()later. createRoottakes the container only. Rendering takes the element. This is why the old pattern of passing a callback as a third argument torenderno longer exists.
import { createRoot } from 'react-dom/client';
import App from './App';
const root = createRoot(document.getElementById('root'));
root.render(<App />);
// Later, for example when a widget is removed from a host page:
// root.unmount();root.unmount() replaces ReactDOM.unmountComponentAtNode(container). Call createRoot once per container. Creating a second root on the same container logs a warning in development, and the two roots would compete for the same DOM nodes.
What "opting in" changes
Switching to createRoot changes more than interruptibility. Four changes show up in practice.
Interruptible rendering
Only updates marked as transitions (or derived from a deferred value) are interruptible. Everything else, such as a click handler calling setState, still renders as an urgent update. So createRoot alone does not make your app faster. It makes the later chapters' tools effective.
You can think of it as three layers:
| Layer | What it does | Required for transitions |
|---|---|---|
| React 18+ package | Provides `useTransition`, `startTransition`, `useDeferredValue` | Yes |
| `createRoot` | Lets the scheduler pause and resume renders | Yes |
| `startTransition` or `useDeferredValue` in your code | Marks which updates may be interrupted | Yes |
If any one layer is missing, you get ordinary synchronous rendering.
Automatic batching
Batching means grouping several state updates into one re-render. React 17 batched only updates made inside React event handlers. With createRoot, React 18 batches updates everywhere, including inside promises, setTimeout callbacks and native event handlers.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const [flag, setFlag] = useState(false);
function handleClick() {
setTimeout(() => {
setCount((c) => c + 1);
setFlag((f) => !f);
// With createRoot: one re-render.
// With the legacy root: two re-renders.
}, 0);
}
return (
<button onClick={handleClick} style={{ color: flag ? 'blue' : 'black' }}>
Count: {count}
</button>
);
}This is usually a free improvement. Rarely, code reads the DOM right after a state update and depends on the old, unbatched behavior. In that case, wrap the update in flushSync from react-dom to force a synchronous render:
import { flushSync } from 'react-dom';
function addItem(setItems, setScrollTarget, item) {
flushSync(() => {
setItems((items) => [...items, item]);
});
// The DOM now contains the new item.
flushSync(() => {
setScrollTarget(item.id);
});
}Use flushSync sparingly. It bypasses the scheduling that makes concurrent rendering useful.
Stricter Strict Mode in development
If your app uses <StrictMode>, React 18 with createRoot adds a development-only check. After a component mounts for the first time, React simulates unmounting and remounting it, which runs effects, cleanup, and effects again. This tests that your effects clean up properly. Production builds do not do this.
If a useEffect that subscribes to something or fetches data now runs twice on mount in development, the cause is usually a missing cleanup function. It is not a bug introduced by createRoot itself. This matters for the rest of the tutorial, because concurrent rendering can also render a component more than once before committing it. Components that are pure and effects that clean up behave correctly in both cases.
Server-rendered apps use hydrateRoot
If the HTML comes from the server and React attaches to it, use hydrateRoot instead of ReactDOM.hydrate:
import { hydrateRoot } from 'react-dom/client';
import App from './App';
const container = document.getElementById('root');
hydrateRoot(container, <App />);hydrateRoot takes the initial element as its second argument, because hydration must match the server HTML on the first render. It also creates a concurrent root, so transitions work after hydration completes. Do not call createRoot on a container that already holds server-rendered markup. React would discard that markup and render from scratch.
Migration steps
The decision for each entry point in your app looks like this:
A safe sequence for an existing project:
- Upgrade
reactandreact-domtogether to the same major version. - Replace
ReactDOM.renderwithcreateRootandroot.render. - Replace
ReactDOM.hydratewithhydrateRoot, if you server-render. - Replace
unmountComponentAtNodewithroot.unmount(). - Run the app in development with
<StrictMode>and fix effects that lack cleanup. - Run your tests and look for changed timing, covered below.
Checking which root you have
You can confirm the setup without reading the whole codebase. First check the installed versions:
npm ls react react-domBoth should report the same version, 18.0.0 or later. Then search your entry file for the import:
grep -rn "react-dom" src/index.js src/main.jsxYou want to see react-dom/client. A bare react-dom import with render or hydrate means a legacy root.
A behavioral check is also possible. In a component, log inside the render body while a transition runs. With a concurrent root, the same transition may log more than once, or log renders that never commit, because React can start and abandon work. A legacy root never abandons a render.
Testing and tooling
Test setups need a small adjustment. React Testing Library 13 and later uses createRoot internally. If you use an older version with React 18, your tests silently run on a legacy root and also print a warning. Upgrade the library to match.
If you render with createRoot directly in a test, tell React you are in a test environment and wrap updates in act:
import { createRoot } from 'react-dom/client';
import { act } from 'react';
import App from './App';
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
test('renders the app', async () => {
const container = document.createElement('div');
document.body.appendChild(container);
const root = createRoot(container);
await act(async () => {
root.render(<App />);
});
expect(container.textContent).not.toBe('');
await act(async () => {
root.unmount();
});
container.remove();
});act is imported from react in React 18.3 and 19. In earlier 18.x versions, import it from react-dom/test-utils. Without act, updates may not have been applied when your assertions run, because concurrent rendering schedules work instead of doing it immediately.
Common errors
- Importing from the wrong module.
import { createRoot } from 'react-dom'givesundefinedin React 18 and later. Usereact-dom/client. - Mismatched package versions.
react@18withreact-dom@17has nocreateRoot. Upgrade both. - Calling
createRooton every render. Create the root once, at module scope or in setup code. In a widget that mounts into a host page, keep the root in a variable and reuse it. - Using
createRooton server-rendered markup. This causes a full client re-render. UsehydrateRoot. - Expecting speed from the root alone. Without
startTransition,useTransitionoruseDeferredValuein your code, a slow update stays slow.
What comes next
With a concurrent root in place, the next chapters build on it. You will mark updates as transitions with startTransition, read their status with useTransition, and defer values with useDeferredValue.
Exercise
A teammate upgraded to React 18 and wrapped a state update in startTransition, but typing in the app is still laggy and renders are never interrupted. The entry file contains ReactDOM.render(<App />, document.getElementById('root')) with import ReactDOM from 'react-dom'. What is the cause, and what is the fix?
Show answer
The app still uses a legacy root, so React renders synchronously and startTransition has nothing to interrupt. The fix is to import createRoot from react-dom/client, call const root = createRoot(document.getElementById('root')), and then root.render(<App />). If the HTML is server-rendered, use hydrateRoot(container, <App />) instead. In development, also check effects for missing cleanup, since Strict Mode now runs them twice on mount.
Exercise
After moving to createRoot, two setState calls inside a setTimeout now cause one re-render instead of two, and a line of code that read the DOM right after the first call sees stale content. Which feature explains this, and how do you restore the old behavior for that one update?
Show answer
Automatic batching explains it. With a concurrent root, React batches updates inside timeouts, promises and native handlers. Wrap the update that must apply immediately in flushSync from react-dom, then read the DOM after it returns. Use it only where needed, because it bypasses concurrent scheduling.