hydrateRoot lets you display React components inside a browser DOM node whose HTML content was previously generated by react-dom/server. hydrateRoot를 사용하면 이전에 react-dom/server로 생성한 HTML 콘텐츠가 있는 브라우저 DOM 노드 내에 React 컴포넌트를 표시할 수 있습니다.

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. hydrateRoot를 호출하여 서버 환경에서 React가 이미 만들어둔 HTML에 React를 “붙입니다”.

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. React는 domNode 내부에 있는 HTML에 붙어서 그 내부의 DOM을 직접 관리할 것입니다. 온전히 React만으로 만든 App에서는 보통 단일 루트 컴포넌트에 대해 hydrateRoot를 단 한 번만 호출할 것입니다.

See more examples below. 아래에서 더 많은 예시를 확인하세요.

Parameters매개변수

  • domNode: A DOM element that was rendered as the root element on the server. domNode: 서버에서 루트 엘리먼트로 렌더링된 DOM element.

  • reactNode: The “React node” used to render the existing HTML. This will usually be a piece of JSX like <App /> which was rendered with a ReactDOM Server method such as renderToPipeableStream(<App />). reactNode: 앞서 존재하는 HTML에 렌더링하기 위한 “React 노드”. 주로 ReactDOM ServerrenderToPipeableStream(<App />)처럼 메서드로 렌더링된 <App />같은 JSX 조각들입니다.

  • optional options: An object with options for this React root. 선택적 options: React 루트에 옵션을 주기 위한 객체.

  • optional onRecoverableError: Callback called when React automatically recovers from errors. 선택적 onRecoverableError: React가 에러에서 자동으로 회복되었을 때 호출하는 콜백 함수.

  • Canary only optional onCaughtError: Callback called when React catches an error in an Error Boundary. Called with the error caught by the Error Boundary, and an errorInfo object containing the componentStack. Canary only 선택적 onCaughtError: React가 에러 바운더리에서 에러를 포착할 때 호출되는 콜백. 에러 바운더리에서 포착한 errorcomponentStack을 포함하는 errorInfo 객체와 함께 호출됩니다.

  • Canary only optional onUncaughtError: Callback called when an error is thrown and not caught by an Error Boundary. Called with the error that was thrown and an errorInfo object containing the componentStack. Canary only 선택적 onUncaughtError: 에러가 발생했지만 에러 바운더리에 잡히지 않은 경우 호출되는 콜백입니다. 발생한 errorcomponentStack을 포함하는 errorInfo 객체와 함께 호출됩니다.

  • optional onRecoverableError: Callback called when React automatically recovers from errors. Called with the error React throws, and an errorInfo object containing the componentStack. Some recoverable errors may include the original error cause as error.cause. 선택적 onRecoverableError: React가 오류로부터 자동으로 복구할 때 호출되는 콜백입니다. React가 던지는 error와, componentStack을 포함하는 errorInfo 객체와 함께 호출됩니다. 복구 가능한 일부 오류에는 원래의 오류 원인이 error.cause로 포함될 수 있습니다.

  • optional identifierPrefix: A string prefix React uses for IDs generated by useId. Useful to avoid conflicts when using multiple roots on the same page. Must be the same prefix as used on the server. 선택적 identifierPrefix: React가 ID로 사용하는 접두사로 useId로 만들어진 값. 한 페이지에 여러 루트를 사용할 경우 충돌을 피하는 데에 유용합니다. 반드시 서버에서 사용한 것과 동일한 값이어야 합니다.

Returns반환값

hydrateRoot returns an object with two methods: render and unmount. hydrateRoot는 두 메서드가 포함된 객체를 반환합니다: renderunmount.

Caveats주의사항

  • hydrateRoot() expects the rendered content to be identical with the server-rendered content. You should treat mismatches as bugs and fix them. hydrateRoot()는 서버에서 렌더링된 내용과 후에 렌더링된 내용이 동일할 것을 기대합니다. 동일하지 않은 부분들은 버그로 인식하고 직접 고쳐줘야 합니다.

  • In development mode, React warns about mismatches during hydration. There are no guarantees that attribute differences will be patched up in case of mismatches. This is important for performance reasons because in most apps, mismatches are rare, and so validating all markup would be prohibitively expensive. 개발 환경에서는 React가 hydration 중에 동일하지 않은 부분에 대해 경고해 줍니다. 속성이 동일하지 않을 경우 해당 속성이 올바르게 적용될 것이라고 보장할 수 없습니다. 마크업이 동일하지 않는 경우는 드물고, 모든 마크업을 검증하는 비용은 굉장히 비싸므로, 이 동작은 성능상 중요합니다.

  • You’ll likely have only one hydrateRoot call in your app. If you use a framework, it might do this call for you. hydrateRoot는 App에서 단 한 번만 호출하게 될 것입니다. 만약 프레임워크를 사용한다면 프레임워크가 대신 호출해줄 수도 있습니다.

  • If your app is client-rendered with no HTML rendered already, using hydrateRoot() is not supported. Use createRoot() instead. App이 미리 렌더링된 HTML 없이 클라이언트에서만 렌더링하는 경우에는 hydrateRoot()를 쓸 수 없습니다. 대신 createRoot()를 사용해주세요.


root.render(reactNode)

Call root.render to update a React component inside a hydrated React root for a browser DOM element. hydrate된 React 루트부터 내부 컴포넌트를 새로운 React 컴포넌트로 갱신하려면 root.render를 호출하세요. 브라우저 DOM 요소들도 함께 갱신됩니다.

root.render(<App />);

React will update <App /> in the hydrated root. React는 hydrate된 root부터 내부를 <App />으로 갱신합니다.

See more examples below. 아래에서 더 많은 예시를 확인하세요.

Parameters매개변수

  • reactNode: A “React node” that you want to update. This will usually be a piece of JSX like <App />, but you can also pass a React element constructed with createElement(), a string, a number, null, or undefined. reactNode: 갱신하고 싶은 “React 노드”. 주로 <App />과 같은 JSX를 매개변수로 넘기지만, createElement()로 만든 React 엘리먼트나 문자열, 숫자, null, undefined 등을 넘겨도 됩니다.

Returns반환값

root.render returns undefined. root.renderundefined를 반환합니다.

Caveats주의사항

  • 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. hydrate가 끝나기 전에 root.render를 호출하면 React는 서버에서 렌더링된 HTML을 모두 없애고 클라이언트에서 렌더링된 컴포넌트들로 완전히 교체합니다.

root.unmount()

Call root.unmount to destroy a rendered tree inside a React root. root.unmount를 호출해 React 루트부터 그 하위에 렌더링된 트리를 삭제합니다.

root.unmount();

An app fully built with React will usually not have any calls to root.unmount. 온전히 React만으로 만든 앱은 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. 주로 React 루트부터 혹은 그 상위에서부터 시작된 DOM node들을 다른 코드에 의해 DOM에서 삭제되어야 하는 경우 유용합니다. 예를 들어, jQuery 탭 패널이 활성화 되어 있지 않은 탭을 DOM에서 지운다고 가정해봅시다. 탭이 지워지면, React 루트와 그 내부를 포함해 그 안의 모든 것이 지워지게 되고 DOM에서 또한 지워지게 됩니다. root.unmount를 호출해 React에게 삭제된 컨텐츠들을 “그만” 다루라고 알려주어야 합니다. 그렇지 않으면 삭제되어버린 React 루트 내부의 컴포넌트들은 삭제되지 않을 것이며, “구독”처럼 컴퓨팅 자원을 자유롭게 놓아주지 못하게 됩니다.

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. root.unmount를 호출하면 루트 내부의 모든 컴포넌트를 언마운트하고 루트 DOM 노드에서 React를 “떼어”냅니다. 루트 내부의 이벤트 핸들러와 state까지 모두 포함해 언마운트 및 삭제됩니다.

Parameters매개변수

root.unmount does not accept any parameters. root.unmount는 매개변수를 받지 않습니다.

Returns반환값

root.unmount returns undefined. root.unmountundefined를 반환합니다.

Caveats주의사항

  • Calling root.unmount will unmount all the components in the tree and “detach” React from the root DOM node. root.unmount를 호출하면 루트부터 그 안의 모든 컴포넌트가 언마운트되고 루트 DOM 노드에서 React를 “떼어냅니다.”

  • 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를 한번 호출한 이후엔 root.render를 루트에 다시 사용할 수 없습니다. 언마운트된 루트에 다시 root.render를 호출하려고 한다면 “마운트되지 않은 루트를 업데이트할 수 없습니다.”라는 에러를 던지게 됩니다.


Usage사용법

Hydrating server-rendered HTML서버에서 렌더링된 HTML을 hydrate하기

If your app’s HTML was generated by react-dom/server, you need to hydrate it on the client. 앱의 HTML을 react-dom/server로 생성했다면, 클라이언트에서 hydrate해주어야 합니다.

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. 이렇게 하면 서버 HTML을 브라우저 DOM 노드에서 React 컴포넌트를 이용해 hydrate 해줍니다. 주로 앱을 시작할 때 단 한 번 실행하게 될 것입니다. 프레임워크를 사용중이라면 프레임워크가 알아서 실행해줄 것입니다.

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. 앱을 hydrate하기 위해 React는 서버에서 만들어 진 HTML에 컴포넌트의 로직을 “붙입니다”. Hydration을 거치면 서버에서 만들어진 초기 HTML 스냅샷이 브라우저에서 완전히 인터랙티브한 앱으로 바뀌게 됩니다.

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

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

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. hydrateRoot를 다시 호출하거나 다른 곳에서 더 호출할 필요는 없습니다. 이 시점부터 React가 애플리케이션의 DOM을 다루게 됩니다. UI를 갱신하기 위해선 대신 useState를 사용하세요.

Pitfall | 함정

The React tree you pass to hydrateRoot needs to produce the same output as it did on the server. hydrateRoot에 전달한 React 트리는 서버에서 만들었던 React 트리 결과물과 동일해야 합니다.

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. 이는 사용자 경험을 위해서 중요합니다. 유저는 서버에서 만들어진 HTML을 JavaScript 코드가 로드될 때까지 둘러보게 됩니다. 서버 렌더링은 HTML 스냅샷을 보여줌으로써 앱의 로딩이 더 빠르게 느껴지도록 합니다. 갑자기 다른 컨텐츠를 보여주게 되면 이러한 환상이 깨져버릴 것입니다. 따라서 서버에서 렌더링한 결과물과 클라이언트에서 최초로 렌더링한 결과물이 같아야 하는 것입니다.

The most common causes leading to hydration errors include: 다음은 hydration 에러가 발생하는 대표적인 사례들입니다:

  • Extra whitespace (like newlines) around the React-generated HTML inside the root node. 루트 노드 안쪽에서 React로 작성된 HTML 주위에 새 줄(new line) 등의 추가적인 공백이 있는 경우.

  • Using checks like typeof window !== 'undefined' in your rendering logic. typeof window !== 'undefined'과 같은 조건을 렌더링 로직에서 사용한 경우.

  • Using browser-only APIs like window.matchMedia in your rendering logic. window.matchMedia와 같은 브라우저 전용 API를 렌더링 로직에 사용한 경우.

  • Rendering different data on the server and the client. 서버와 클라이언트에서 서로 다른 데이터를 렌더링한 경우.

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. React는 몇몇 hydration 에러는 복구하긴 하지만, 다른 버그들과 마찬가지로 반드시 고쳐줘야 합니다. 운이 좋으면 그저 느려지기만 할 뿐이겠지만, 최악의 경우 이벤트 핸들러가 다른 엉뚱한 엘리먼트에 붙게 될 수도 있습니다.


Hydrating an entire document문서 전체를 hydrate하기

Apps fully built with React can render the entire document as JSX, including the <html> tag: 앱을 온전히 React만으로 작성한 경우 <html> 태그를 포함해 JSX로 된 전체 문서를 렌더링할 수 있습니다.

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: 전체 문서를 hydrate하기 위해선 글로벌 변수인 documenthydrateRoot의 첫번째 인자로 넘기세요:

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

hydrateRoot(document, <App />);

Suppressing unavoidable hydration mismatch errors불가피한 hydration 불일치 에러 억제하기

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. 어떤 엘리먼트의 속성이나 텍스트 컨텐츠가 서버와 클라이언트에서 서로 다를 수밖에 없는 경우(예: 타임스탬프), hydration 불일치 경고를 안보이게 할 수도 있습니다.

To silence hydration warnings on an element, add suppressHydrationWarning={true}: 해당 element에서 hydration 경고를 끄기 위해서는 suppressHydrationWarning={true}를 추가하세요:

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. Unless it’s text content, React still won’t attempt to patch it up, so it may remain inconsistent until future updates. 이것은 한 단계 아래까지만 적용되며, 예외적인 탈출구일 뿐입니다. 남용하지 마세요. 텍스트 컨텐츠가 아닌 한 React는 잘못된 부분을 수정하지 않을 것이며, 갱신이 일어나기 전까지는 불일치한 상태로 남아있을 것입니다.


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: 의도적으로 서버와 클라이언트에서 서로 다른 내용을 렌더링하길 원한다면, 서버와 클라이언트에서 서로 다른 방법으로 렌더링하면 됩니다. 클라이언트에서 다른 것을 렌더링하고자 하는 컴포넌트에서, Effect에서 true로 할당되는 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>
  );
}

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. 이렇게 하면 처음엔 서버와 동일한 결과물을 렌더링해서 불일치 문제를 피하고, 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. 이 방법은 두 번 렌더링해야 하므로 상대적으로 hydration이 느려집니다. 통신 상태가 느릴 경우의 사용자 경험을 유의하세요. 초기 HTML이 렌더링되고 한참 이후에야 JavaScript 코드를 불러오게 될 수 있고, 이 경우 hydration 이후 즉시 다른 UI를 렌더링하게 되면 사용자로서는 UI가 삐걱거리는 것처럼 인식될 수도 있습니다.


Updating a hydrated root componenthydrate된 루트 컴포넌트 업데이트하기

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. 루트의 hydrate가 끝난 이후에 root.render를 호출해 루트 컴포넌트를 업데이트 할 수 있습니다. createRoot와 달리 초기 컨텐츠가 이미 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: hydrate 후 어떤 시점에 root.render를 호출했을 때 컴포넌트의 트리 구조가 이전에 렌더링했던 구조와 일치한다면, React는 state를 그대로 유지합니다. 다음 예제에서 input에 어떻게 타이핑하든 관계 없이, 매 초 반복되는 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);

It is uncommon to call root.render on a hydrated root. Usually, you’ll update state inside one of the components instead. hydrate된 루트에 root.render를 호출하는 것은 흔한 일은 아닙니다. 내부 컴포넌트 중 한 곳에서 state를 업데이트하는 것이 일반적입니다.

Show a dialog for uncaught errors잡히지 않은 오류에 대한 대화 상자 표시

Canary

onUncaughtError is only available in the latest React Canary release. onUncaughtError는 최근 릴리즈된 React Canary 버전에서만 사용할 수 있습니다.

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: 기본적으로 React는 잡히지 않은 모든 오류를 콘솔에 기록합니다. 자체 오류 보고를 구현하려면 선택 사항인 onUncaughtError 루트 옵션을 제공할 수 있습니다:

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: onUncaughtError 옵션은 두 개의 인수를 사용하여 호출되는 함수입니다:

  1. The error that was thrown. 발생한 error.

  2. An errorInfo object that contains the componentStack of the error. 오류의 componentStack을 포함하는 errorInfo 객체.

You can use the onUncaughtError root option to display error dialogs: onUncaughtError 루트 옵션을 사용하여 오류 대화 상자를 표시할 수 있습니다:

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 errorsError Boundary의 오류 표시하기

Canary

onCaughtError is only available in the latest React Canary release. onCaughtError는 최근 릴리즈된 React Canary 버전에서만 사용할 수 있습니다.

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: 기본적으로 React는 오류 바운더리에 의해 포착된 모든 오류를 console.error에 기록합니다. 이 동작을 재정의하려면, Error Boundary에 의해 포착된 오류에 대해 선택적 onCaughtError 루트 옵션을 제공할 수 있습니다:

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 onUncaughtError option is a function called with two arguments: onUncaughtError 옵션은 두 개의 인수를 사용하여 호출되는 함수입니다:

  1. The error that was thrown. 발생한 error.

  2. An errorInfo object that contains the componentStack of the error. 오류의 componentStack을 포함하는 errorInfo 객체.

You can use the onCaughtError root option to display error dialogs or filter known errors from logging: onCaughtError 루트 옵션을 사용하여 오류 대화 상자를 표시하거나 로깅에서 알려진 오류를 필터링할 수 있습니다:

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복구 가능한 hydration 불일치 오류에 대한 대화 상자 표시

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: React에서 hydration 불일치가 발생하면 클라이언트에서 렌더링하여 자동으로 복구를 시도합니다. 기본적으로 React는 console.error에 hydration 불일치 오류를 기록합니다. 이 동작을 재정의하려면 선택적 onRecoverableError 루트 옵션을 제공할 수 있습니다:

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: onRecoverableError 옵션은 두 개의 인수를 사용하여 호출되는 함수입니다:

  1. The error React throws. Some errors may include the original cause as error.cause. React가 던지는 error. 일부 오류는 error.cause와 같은 원래의 원인을 포함할 수 있습니다.

  2. An errorInfo object that contains the componentStack of the error. 오류의 componentStack을 포함하는 errorInfo 객체.

You can use the onRecoverableError root option to display error dialogs for hydration mismatches: hydration 불일치에 대한 오류 대화 상자를 표시하려면 onRecoverableError 루트 옵션을 사용할 수 있습니다:

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

const container = document.getElementById("root");
const root = hydrateRoot(container, <App />, {
  onRecoverableError: (error, errorInfo) => {
    reportRecoverableError({
      error,
      cause: error.cause,
      componentStack: errorInfo.componentStack
    });
  }
});

Troubleshooting문제 해결

I’m getting an error: “You passed a second argument to root.render”오류가 발생했습니다: “root.render에 두 번째 인수를 전달했습니다.”

A common mistake is to pass the options for hydrateRoot to root.render(...): 일반적인 실수는 hydrateRoot에 대한 옵션을 root.render(...)로 전달하는 것입니다:

Console
Warning: You passed a second argument to root.render(…) but it only accepts one argument. 경고: root.render(…)에 두 번째 인수를 전달했지만 이 함수는 하나의 인수만 허용합니다.

To fix, pass the root options to hydrateRoot(...), not root.render(...): 이를 수정하려면 루트 옵션을 root.render(...)가 아닌 hydrateRoot(...)로 전달하세요:

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

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