new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

React · API reference · all subjects

react-dom/client

31 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

hydrateRoot function purpose

hydrateRoot lets you display React components inside a browser DOM node whose HTML content was previously generated by react-dom/server.

React browser support

React supports all popular browsers, including Internet Explorer 9 and above. Some polyfills are required for older browsers such as IE 9 and IE 10.

react-dom/client module overview

The react-dom/client APIs let you render React components on the client in the browser. These APIs are typically used at the top level of your app to initialize your React tree. A framework may call them for you. Most components don't need to import or use them.

hydrateRoot options: onUncaughtError

The onUncaughtError option is an optional callback called when an error is thrown and not caught by an Error Boundary. It is called with two arguments: the error that was thrown and an errorInfo object containing the componentStack.

hydrateRoot options: onRecoverableError

The onRecoverableError option is an optional callback called when React automatically recovers from errors. It is called with two arguments: the error React throws and an errorInfo object containing the componentStack. Some recoverable errors may include the original error cause as error.cause.

hydrateRoot options: identifierPrefix

The identifierPrefix option is an optional string prefix that React uses for IDs generated by useId. It is useful to avoid conflicts when using multiple roots on the same page. The prefix must be the same as the prefix used on the server.

hydrateRoot return value

hydrateRoot returns an object with two methods: render and unmount.

hydrateRoot caveat: matching server and client output

hydrateRoot expects the rendered content to be identical with the server-rendered content. Mismatches should be treated as bugs and fixed. In development mode, React warns about mismatches during hydration, but there are no guarantees that attribute differences will be patched up in case of mismatches due to performance reasons.

hydrateRoot caveat: only one call per app

You will likely have only one hydrateRoot call in your app. If you use a framework, it might do this call for you.

hydrateRoot caveat: not for client-rendered apps

If your app is client-rendered with no HTML rendered already, using hydrateRoot is not supported. Use createRoot instead.

root.render method on hydrated root

Call root.render to update a React component inside a hydrated React root for a browser DOM element. root.render(reactNode) takes a React node parameter (usually JSX like <App />, but can also be a React element constructed with createElement, a string, a number, null, or undefined) and returns undefined.

root.render caveat: calling before hydration completes

If you call root.render before the root has finished hydrating, React will clear the existing server-rendered HTML content and switch the entire root to client rendering.

root.unmount method

Call root.unmount to destroy a rendered tree inside a React root. root.unmount() does not accept any parameters and returns undefined. It unmounts all the components in the root and detaches React from the root DOM node, including removing any event handlers or state in the tree.

root.unmount caveat: cannot re-render after unmount

Once you call root.unmount, you cannot call root.render again on the root. Attempting to call root.render on an unmounted root will throw a 'Cannot update an unmounted root' error.

root.unmount use case

root.unmount 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, if a jQuery tab panel removes inactive tabs from the DOM, 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 clean up and free up resources like subscriptions.

Hydrating entire document with hydrateRoot

Apps fully built with React can render the entire document as JSX, including the <html> tag. To hydrate the entire document, pass the document global as the first argument to hydrateRoot: hydrateRoot(document, <App />)

suppressHydrationWarning prop to silence hydration mismatch warnings

If a single element's attribute or text content is unavoidably different between the server and the client (for example, a timestamp), you can silence the hydration mismatch warning by adding suppressHydrationWarning={true} to the element. This only works one level deep and is intended to be an escape hatch. React will not attempt to patch mismatched text content. Do not overuse it.

Handling different client and server content with two-pass rendering

If you intentionally need to render something different on the server and the client, you can do a two-pass rendering. Components that render something different on the client can read a state variable like isClient, which you can set to true in an Effect. This way the initial render pass will render the same content as the server, avoiding mismatches, but an additional pass will happen synchronously right after hydration. This approach makes hydration slower because your components have to render twice, so be mindful of the user experience on slow connections.

root.render preserves state on hydrated root

After the root has finished hydrating, you can call root.render to update the root React component. If you call root.render at some point after hydration and the component tree structure matches up with what was previously rendered, React will preserve the state.

Common mistake: passing options to root.render instead of hydrateRoot

A common mistake is to pass the options for hydrateRoot to root.render. root.render only accepts one argument (the reactNode). To fix, pass the root options to hydrateRoot, not root.render. Example: const root = hydrateRoot(container, <App />, {onUncaughtError})

Common hydration mismatch causes

The most common causes leading to hydration errors include: (1) Extra whitespace (like newlines) around the React-generated HTML inside the root node; (2) Using checks like typeof window !== 'undefined' in rendering logic; (3) Using browser-only APIs like window.matchMedia in rendering logic; (4) Rendering different data on the server and the client.

React hydration error recovery

React recovers from some hydration errors, but you must fix them like other bugs. In the best case, they will lead to a slowdown; in the worst case, event handlers can get attached to the wrong elements.

Example: basic hydrateRoot usage

import { hydrateRoot } from 'react-dom/client'; hydrateRoot(document.getElementById('root'), <App />);

Example: hydrateRoot with all error handlers

import { hydrateRoot } from "react-dom/client"; import App from "./App.js"; import { onCaughtErrorProd, onRecoverableErrorProd, onUncaughtErrorProd, } from "./reportError"; const container = document.getElementById("root"); hydrateRoot(container, <App />, { onCaughtError: onCaughtErrorProd, onRecoverableError: onRecoverableErrorProd, onUncaughtError: onUncaughtErrorProd, });

Example: suppressHydrationWarning usage

export default function App() { return ( <h1 suppressHydrationWarning={true}> Current Date: {new Date().toLocaleDateString()} </h1> ); }

Example: two-pass rendering with isClient state

import { useState, useEffect } from "react"; export default function App() { const [isClient, setIsClient] = useState(false); useEffect(() => { setIsClient(true); }, []); return ( <h1> {isClient ? 'Is Client' : 'Is Server'} </h1> ); }

Example: updating hydrated root with root.render

import { hydrateRoot } from 'react-dom/client'; import './styles.css'; import App from './App.js'; const root = hydrateRoot( document.getElementById('root'), <App counter={0} /> ); let i = 0; setInterval(() => { root.render(<App counter={i} />); i++; }, 1000);

hydrateRoot signature and basic usage

hydrateRoot lets you display React components inside a browser DOM node whose HTML content was previously generated by react-dom/server. The function signature is: const root = hydrateRoot(domNode, reactNode, options?). It attaches React to existing HTML that was already rendered by React in a server environment. React will attach to the HTML that exists inside the domNode and take over managing the DOM inside it. An app fully built with React will usually only have one hydrateRoot call with its root component.

hydrateRoot parameters

hydrateRoot accepts three parameters: (1) domNode - a DOM element that was rendered as the root element on the server; (2) reactNode - the React node used to render the existing HTML, usually a piece of JSX like <App /> which was rendered with a ReactDOM Server method such as renderToPipeableStream(<App />); (3) options (optional) - an object with options for the React root.

hydrateRoot options: onCaughtError

The onCaughtError option is an optional callback called when React catches an error in an Error Boundary. It is called with two arguments: the error caught by the Error Boundary, and an errorInfo object containing the componentStack.

react-dom/client entry point

react-dom/client is an entry point in the react-dom package that contains APIs to render React components on the client, which means in the browser.

Give your agent this brain