Deprecated | 지원 중단

This API will be removed in a future major version of React. 이 API는 향후 React의 주요 버전에서 제거될 예정입니다.

In React 18, hydrate was replaced by hydrateRoot. Using hydrate in React 18 will warn that your app will behave as if it’s running React 17. Learn more here. React 18에서 hydratehydrateRoot로 대체되었습니다. React 18에서 hydrate 를 사용하면 앱이 React 17을 실행하는 것처럼 동작한다는 경고가 표시됩니다. 여기에서 자세히 알아보세요.

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

hydrate(reactNode, domNode, callback?)

Reference참조

hydrate(reactNode, domNode, callback?)

Call hydrate in React 17 and below to “attach” React to existing HTML that was already rendered by React in a server environment. 서버 환경에서 React가 이미 렌더링한 기존 HTML에 React를 “연결”하려면 React 17이하에서 hydrate를 호출하세요.

import { hydrate } from 'react-dom';

hydrate(reactNode, domNode);

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 hydrate call with its root component. React는 domNode 내부에 존재하는 HTML에 첨부하고 그 내부의 DOM을 관리합니다. React로 완전히 빌드된 앱은 일반적으로 root 컴포넌트와 hydrate 호출이 한 번만 있습니다.

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

Parameters매개변수

  • 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 renderToString(<App />) in React 17. reactNode : 기존 HTML을 렌더링하는 데 사용되는 ‘React node’입니다. 일반적으로 React 17에서 renderToString(<App />) 과 같은 ReactDOM Server 메서드로 렌더링 된 <App /> 과 같은 JSX가 됩니다.

  • domNode: A DOM element that was rendered as the root element on the server. domNode : 서버에서 루트 요소로 렌더링된 DOM 요소입니다.

  • optional: callback: A function. If passed, React will call it after your component is hydrated. 선택 사항: callback: 함수. 전달되면 React는 컴포넌트가 hydrate된 후에 호출합니다.

Returns반환값

hydrate returns null. hydrate 는 null을 반환합니다.

Caveats주의사항

  • hydrate expects the rendered content to be identical with the server-rendered content. React can patch up differences in text content, but you should treat mismatches as bugs and fix them. hydrate 는 렌더링된 콘텐츠가 서버에서 렌더링된 콘텐츠와 동일할 것으로 기대합니다. React는 텍스트 콘텐츠의 차이를 해결할 수 있지만, 불일치를 버그로 간주하고 수정해야 합니다.

  • 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 hydrate call in your app. If you use a framework, it might do this call for you. 앱에 hydrate 호출이 하나만 있을 가능성이 높습니다. 프레임워크를 사용하는 경우 프레임워크가 이 호출을 대신 수행할 수 있습니다.

  • If your app is client-rendered with no HTML rendered already, using hydrate() is not supported. Use render() (for React 17 and below) or createRoot() (for React 18+) instead. 앱이 이미 렌더링된 HTML 없이 클라이언트로 렌더링되는 경우 hydrate() 사용은 지원되지 않습니다. 대신 render() (React 17 이하 버전) 또는 createRoot() (React 18 이상 버전)를 사용하세요.


Usage사용법

Call hydrate to attach a React component into a server-rendered browser DOM node. 서버에서 렌더링된 브라우저 DOM 노드React 컴포넌트를 연결하려면 hydrate를 호출하세요.

import { hydrate } from 'react-dom';

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

Using hydrate() to render a client-only app (an app without server-rendered HTML) is not supported. Use render() (in React 17 and below) or createRoot() (in React 18+) instead. 클라이언트 전용 앱(서버 렌더링 HTML이 없는 앱)을 렌더링하는 데 hydrate()를 사용하는 것은 지원되지 않습니다. 대신 render() (React 17 이하 버전) 또는 createRoot() (React 18 이상 버전)를 사용하세요.

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

In React, “hydration” is how React “attaches” to existing HTML that was already rendered by React in a server environment. During hydration, React will attempt to attach event listeners to the existing markup and take over rendering the app on the client. React에서 “hydration”은 서버 환경에서 이미 렌더링한 기존 HTML에 “연결”하는 방식입니다. hydration이 진행되는 동안 React는 기존 마크업에 이벤트 리스너를 연결하고 클라이언트에서 앱 렌더링을 이어받으려고 시도합니다.

In apps fully built with React, you will usually only hydrate one “root”, once at startup for your entire app. React로 완전히 빌드된 앱에서는 일반적으로 전체 앱의 시작 시 한 번, 하나의 “root”에만 hydrate합니다.

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

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

Usually you shouldn’t need to call hydrate 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. 보통은 hydrate를 다시 호출하거나 더 많은 위치에서 호출할 필요가 없습니다. 이 시점부터 React는 애플리케이션의 DOM을 관리하게 됩니다. UI를 업데이트하기 위해 컴포넌트는 state를 사용합니다.

For more information on hydration, see the docs for hydrateRoot. hydration에 대한 자세한 내용은 hydrateRoot 문서를 참조하세요.


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}: 요소에서 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: 서버와 클라이언트에서 의도적으로 다른 것을 렌더링해야 하는 경우 투패스 렌더링을 수행할 수 있습니다. 클라이언트에서 다른 것을 렌더링하는 컴포넌트는 isClient와 같은 state 변수를 읽을 수 있으며, 이를 Effect에서 true로 설정할 수 있습니다:

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 feel jarring to the user. 이 접근 방식은 컴포넌트가 두 번 렌더링해야 하므로 hydration 속도가 느려집니다. 느린 연결 상태에서의 사용자 경험에 유의하세요. JavaScript 코드는 초기 HTML 렌더링보다 상당히 늦게 로드될 수 있으므로 hydration 직후에 다른 UI를 렌더링하면 사용자에게 어색하게 느껴질 수 있습니다.