hydrateRoot·续

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

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

hydrateRoot(document, );


---

### 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}`:

```html public/index.html
<!--
  HTML content inside <div id="root">...</div>
  was generated from App by react-dom/server.
-->
<div id="root"><h1>Current Date: <!-- -->01/01/2020</h1></div>

```js src/index.js import './styles.css'; import { hydrateRoot } from 'react-dom/client'; import App from './App.js';

hydrateRoot(document.getElementById('root'), );


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

This only works one level deep, and is intended to be an escape hatch. Don’t overuse it. React will not attempt to patch mismatched text content.


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:

```html public/index.html

Is Server


```js src/index.js
import './styles.css';
import { hydrateRoot } from 'react-dom/client';
import App from './App.js';

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

```js {expectedErrors: {'react-compiler': [7]}} src/App.js active import { useState, useEffect } from "react";

export default function App() { const [isClient, setIsClient] = useState(false);

useEffect(() => { setIsClient(true); }, []);

return (

{isClient ? 'Is Client' : 'Is Server'}

); }


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.

Use this approach when you want the client-rendered content to be different from the initial server-rendered HTML.

If a component should render only in the browser, call [`use(browser())`](/reference/react/use#use-browser) instead of waiting for an Effect.

> [!WARNING]
>
> 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`](#root-render) to update the root React component. **Unlike with [`createRoot`](/reference/react-dom/client/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.](/learn/preserving-and-resetting-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:

```html public/index.html
<!--
  All HTML content inside <div id="root">...</div> was
  generated by rendering <App /> with react-dom/server.
-->
<div id="root"><h1>Hello, world! <!-- -->0</h1><input placeholder="Type something here"/></div>

```js src/index.js active import { hydrateRoot } from 'react-dom/client'; import './styles.css'; import App from './App.js';

const root = hydrateRoot( document.getElementById('root'), );

let i = 0; setInterval(() => { root.render(); i++; }, 1000);


```js src/App.js
export default function App({counter}) {
  return (
    <>
      <h1>Hello, world! {counter}</h1>
      <input placeholder="Type something here" />
    </>
  );
}

It is uncommon to call root.render on a hydrated root. Usually, you'll update state inside one of the components 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 options onUncaughtError, onCaughtError and onRecoverableError:

```js [[1, 7, "onCaughtError"], [2, 7, "error", 1], [3, 7, "errorInfo"], [4, 11, "componentStack", 15]] import { hydrateRoot } from "react-dom/client"; import App from "./App.js"; import { reportCaughtError } from "./reportError";

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


The &lt;CodeStep step={1}>onCaughtError&lt;/CodeStep> option is a function called with two arguments:

1. The &lt;CodeStep step={2}>error&lt;/CodeStep> that was thrown.
2. An &lt;CodeStep step={3}>errorInfo&lt;/CodeStep> object that contains the &lt;CodeStep step={4}>componentStack&lt;/CodeStep> of the error.

Together with `onUncaughtError` and `onRecoverableError`, you can implement your own error reporting system:

```js src/reportError.js
function reportError({ type, error, errorInfo }) {
  // The specific implementation is up to you.
  // `console.error()` is only used for demonstration purposes.
  console.error(type, error, "Component Stack: ");
  console.error("Component Stack: ", errorInfo.componentStack);
}

export function onCaughtErrorProd(error, errorInfo) {
  if (error.message !== "Known error") {
    reportError({ type: "Caught", error, errorInfo });
  }
}

export function onUncaughtErrorProd(error, errorInfo) {
  reportError({ type: "Uncaught", error, errorInfo });
}

export function onRecoverableErrorProd(error, errorInfo) {
  reportError({ type: "Recoverable", error, errorInfo });
}

```js src/index.js active import { hydrateRoot } from "react-dom/client"; import App from "./App.js"; import { onCaughtErrorProd, onRecoverableErrorProd, onUncaughtErrorProd, } from "./reportError";

const container = document.getElementById("root"); hydrateRoot(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, });


```js src/App.js
import { Component, useState } from "react";

function Boom() {
  foo.bar = "baz";
}

class ErrorBoundary extends Component {
  state = { hasError: false };

static getDerivedStateFromError(error) {
    return { hasError: true };
  }

render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }
    return this.props.children;
  }
}

export default function App() {
  const [triggerUncaughtError, settriggerUncaughtError] = useState(false);
  const [triggerCaughtError, setTriggerCaughtError] = useState(false);

return (
    <>
      <button onClick={() => settriggerUncaughtError(true)}>
        Trigger uncaught error
      </button>
      {triggerUncaughtError && <Boom />}
      <button onClick={() => setTriggerCaughtError(true)}>
        Trigger caught error
      </button>
      {triggerCaughtError && (
        <ErrorBoundary>
          <Boom />
        </ErrorBoundary>
      )}
    </>
  );
}

```html public/index.html hidden

My app
Server content before hydration.

## 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(...)`:
```js {2,5}
// 🚩 Wrong: root.render only takes one argument.
root.render(App, {onUncaughtError});

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

Sitemap

Overview of all docs pages