A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://18.react.dev/reference/react-dom/client/hydrateRoot below:

hydrateRoot – React

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

const root = hydrateRoot(domNode, reactNode, options?)

Reference hydrateRoot(domNode, reactNode, options?)

Call hydrateRoot to “attach” React to existing HTML that was already rendered by React in a server environment.

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

const domNode = document.getElementById('root');

const root = hydrateRoot(domNode, reactNode);

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.

See more examples below.

Parameters Returns

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

Caveats root.render(reactNode)

Call root.render to update a React component inside a hydrated React root for a browser DOM element.

React will update <App /> in the hydrated root.

See more examples below.

Parameters Returns

root.render returns undefined.

Caveats root.unmount()

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

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

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 Usage Hydrating server-rendered HTML

If your app’s HTML was generated by react-dom/server, you need to hydrate it on the client.

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

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

This will hydrate the server HTML inside the browser DOM node with the React component for your app. Usually, you will do it once at startup. If you use a framework, it might do this behind the scenes for you.

To hydrate your app, React will “attach” your components’ logic to the initial generated HTML from the server. Hydration turns the initial HTML snapshot from the server into a fully interactive app that runs in the browser.

You shouldn’t need to call hydrateRoot again or to call it in more places. From this point on, React will be managing the DOM of your application. To update the UI, your components will use state instead.

Pitfall

The React tree you pass to hydrateRoot needs to produce the same output as it did on the server.

This is important for the user experience. The user will spend some time looking at the server-generated HTML before your JavaScript code loads. Server rendering creates an illusion that the app loads faster by showing the HTML snapshot of its output. Suddenly showing different content breaks that illusion. This is why the server render output must match the initial render output on the client.

The most common causes leading to hydration errors include:

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

Hydrating an entire document

Apps fully built with React can render the entire document as JSX, including the <html> tag:

function App() {

return (

<html>

<head>

<meta charSet="utf-8" />

<meta name="viewport" content="width=device-width, initial-scale=1" />

<link rel="stylesheet" href="/styles.css"></link>

<title>My app</title>

</head>

<body>

<Router />

</body>

</html>

);

}

To hydrate the entire document, pass the document global as the first argument to hydrateRoot:

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

import App from './App.js';

hydrateRoot(document, <App />);

Suppressing unavoidable hydration mismatch errors

If a single element’s attribute or text content is unavoidably different between the server and the client (for example, a timestamp), you may silence the hydration mismatch warning.

To silence hydration warnings on an element, add suppressHydrationWarning={true}:

This only works one level deep, and is intended to be an escape hatch. Don’t overuse it. Unless it’s text content, React still won’t attempt to patch it up, so it may remain inconsistent until future updates.

Handling different client and server content

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.

Pitfall

This approach makes hydration slower because your components have to render twice. Be mindful of the user experience on slow connections. The JavaScript code may load significantly later than the initial HTML render, so rendering a different UI immediately after hydration may also feel jarring to the user.

Updating a hydrated root component

After the root has finished hydrating, you can call root.render to update the root React component. Unlike with createRoot, you don’t usually need to do this because the initial content was already rendered as HTML.

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. Notice how you can type in the input, which means that the updates from repeated render calls every second in this example are not destructive:

It is uncommon to call root.render on a hydrated root. Usually, you’ll update state inside one of the components instead.

Show a dialog for uncaught errors Canary

onUncaughtError is only available in the latest React Canary release.

By default, React will log all uncaught errors to the console. To implement your own error reporting, you can provide the optional onUncaughtError root option:

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

const root = hydrateRoot(

document.getElementById('root'),

<App />,

{

onUncaughtError: (error, errorInfo) => {

console.error(

'Uncaught error',

error,

errorInfo.componentStack

);

}

}

);

root.render(<App />);

The onUncaughtError option is a function called with two arguments:

  1. The error that was thrown.
  2. An errorInfo object that contains the componentStack of the error.

You can use the onUncaughtError root option to display error dialogs:

import { hydrateRoot } from "react-dom/client";
import App from "./App.js";
import {reportUncaughtError} from "./reportError";
import "./styles.css";
import {renderToString} from 'react-dom/server';

const container = document.getElementById("root");
const root = hydrateRoot(container, <App />, {
  onUncaughtError: (error, errorInfo) => {
    if (error.message !== 'Known error') {
      reportUncaughtError({
        error,
        componentStack: errorInfo.componentStack
      });
    }
  }
});

Displaying Error Boundary errors Canary

onCaughtError is only available in the latest React Canary release.

By default, React will log all errors caught by an Error Boundary to console.error. To override this behavior, you can provide the optional onCaughtError root option for errors caught by an Error Boundary:

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

const root = hydrateRoot(

document.getElementById('root'),

<App />,

{

onCaughtError: (error, errorInfo) => {

console.error(

'Caught error',

error,

errorInfo.componentStack

);

}

}

);

root.render(<App />);

The onCaughtError option is a function called with two arguments:

  1. The error that was caught by the boundary.
  2. An errorInfo object that contains the componentStack of the error.

You can use the onCaughtError root option to display error dialogs or filter known errors from logging:

import { hydrateRoot } from "react-dom/client";
import App from "./App.js";
import {reportCaughtError} from "./reportError";
import "./styles.css";

const container = document.getElementById("root");
const root = hydrateRoot(container, <App />, {
  onCaughtError: (error, errorInfo) => {
    if (error.message !== 'Known error') {
      reportCaughtError({
        error,
        componentStack: errorInfo.componentStack
      });
    }
  }
});

Show a dialog for recoverable hydration mismatch errors

When React encounters a hydration mismatch, it will automatically attempt to recover by rendering on the client. By default, React will log hydration mismatch errors to console.error. To override this behavior, you can provide the optional onRecoverableError root option:

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

const root = hydrateRoot(

document.getElementById('root'),

<App />,

{

onRecoverableError: (error, errorInfo) => {

console.error(

'Caught error',

error,

error.cause,

errorInfo.componentStack

);

}

}

);

The onRecoverableError option is a function called with two arguments:

  1. The error React throws. Some errors may include the original cause as error.cause.
  2. An errorInfo object that contains the componentStack of the error.

You can use the onRecoverableError root option to display error dialogs for hydration mismatches:

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

A common mistake is to pass the options for hydrateRoot to root.render(...):

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

To fix, pass the root options to hydrateRoot(...), not root.render(...):

// 🚩 Wrong: root.render only takes one argument.

root.render(App, {onUncaughtError});

// ✅ Correct: pass options to createRoot.

const root = hydrateRoot(container, <App />, {onUncaughtError});


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4