Pitfall | 함정

renderToString does not support streaming or waiting for data. See the alternatives. renderToString은 스트리밍 또는 데이터 대기를 지원하지 않습니다. 다른 대안을 확인하세요.

renderToString renders a React tree to an HTML string. renderToString은 React 트리를 HTML 문자열로 렌더링합니다.

const html = renderToString(reactNode, options?)

Reference참조

renderToString(reactNode, options?)

On the server, call renderToString to render your app to HTML. 서버에서 renderToString을 호출하면 앱을 HTML로 렌더링합니다.

import { renderToString } from 'react-dom/server';

const html = renderToString(<App />);

On the client, call hydrateRoot to make the server-generated HTML interactive. 클라이언트에서 hydrateRoot를 호출하면 서버에서 생성된 HTML을 상호작용 가능하게 만듭니다.

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

Parameters매개변수

  • reactNode: A React node you want to render to HTML. For example, a JSX node like <App />. reactNode: HTML로 렌더링하려는 React 노드입니다. 예: <App />과 같은 JSX 노드

  • optional options: An object for server render.

    • 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 passed to hydrateRoot.

Returns반환값

An HTML string. HTML 문자열

Caveats주의사항

  • renderToString has limited Suspense support. If a component suspends, renderToString immediately sends its fallback as HTML. renderToString은 Suspense를 제한적으로 지원합니다. 컴포넌트가 일시 중단되면 renderToString은 즉시 HTML로 폴백을 전송합니다.

  • renderToString works in the browser, but using it in the client code is not recommended. renderToString은 브라우저에서도 작동은 하지만, 클라이언트 코드에서 사용하는 것은 권장하지 않습니다.


Usage사용법

Rendering a React tree as HTML to a stringReact 트리를 HTML 문자열로 렌더링하기

Call renderToString to render your app to an HTML string which you can send with your server response: 앱을 서버 응답과 함께 보낼 수 있는 HTML 문자열로 렌더링하도록 renderToString을 호출하세요:

import { renderToString } from 'react-dom/server';

// The route handler syntax depends on your backend framework
// 라우트 핸들러 구문은 백엔드 프레임워크에 따라 다릅니다.
app.use('/', (request, response) => {
const html = renderToString(<App />);
response.send(html);
});

This will produce the initial non-interactive HTML output of your React components. On the client, you will need to call hydrateRoot to hydrate that server-generated HTML and make it interactive. 이렇게 하면 React 컴포넌트의 초기 비대화형 HTML 출력물이 생성됩니다. 클라이언트에서는 서버에서 생성된 HTML을 hydrate하고 상호작용 가능하게 만들기 위해 hydrateRoot를 호출해야 합니다.

Pitfall | 함정

renderToString does not support streaming or waiting for data. See the alternatives. renderToString은 스트리밍 또는 데이터 대기를 지원하지 않습니다. 대안을 참고하세요.


Alternatives대안

Migrating from renderToString to a streaming method on the serverrenderToString을 스트리밍 메서드로 마이그레이션하기

renderToString returns a string immediately, so it does not support streaming or waiting for data. renderToString은 즉시 문자열을 반환하므로 스트리밍이나 데이터 대기를 지원하지 않습니다.

When possible, we recommend using these fully-featured alternatives: 가능한 모든 기능을 갖춘 다음 대체 서비스 중 하나를 사용할 것을 권장합니다:

You can continue using renderToString if your server environment does not support streams. 서버 환경이 스트림을 지원하지 않는 경우에는 renderToString을 계속 사용할 수 있습니다.


Removing renderToString from the client code클라이언트 코드에서 renderToString 제거하기

Sometimes, renderToString is used on the client to convert some component to HTML. 클라이언트에서 일부 컴포넌트를 HTML로 변환하기 위해 renderToString을 사용하는 경우가 있습니다.

// 🚩 Unnecessary: using renderToString on the client
import { renderToString } from 'react-dom/server';

const html = renderToString(<MyIcon />);
console.log(html); // For example, "<svg>...</svg>"

Importing react-dom/server on the client unnecessarily increases your bundle size and should be avoided. If you need to render some component to HTML in the browser, use createRoot and read HTML from the DOM: 클라이언트에서 react-dom/server를 가져오면 번들 크기가 불필요하게 증가하므로 피해야 합니다. 브라우저에서 일부 컴포넌트를 HTML로 렌더링해야 하는 경우 createRoot를 사용하여 DOM에서 HTML을 읽어오세요:

import { createRoot } from 'react-dom/client';
import { flushSync } from 'react-dom';

const div = document.createElement('div');
const root = createRoot(div);
flushSync(() => {
root.render(<MyIcon />);
});
console.log(div.innerHTML); // For example, "<svg>...</svg>"

The flushSync call is necessary so that the DOM is updated before reading its innerHTML property. flushSync 호출은 innerHTML 속성을 읽기 전에 DOM을 업데이트하기 위해 필요합니다.


Troubleshooting문제 해결

When a component suspends, the HTML always contains a fallback컴포넌트에 Suspense를 도입하면 HTML에 항상 폴백만 보입니다

renderToString does not fully support Suspense. renderToString은 Suspense를 완전히 지원하지 않습니다.

If some component suspends (for example, because it’s defined with lazy or fetches data), renderToString will not wait for its content to resolve. Instead, renderToString will find the closest <Suspense> boundary above it and render its fallback prop in the HTML. The content will not appear until the client code loads. 일부 컴포넌트가 일시 중단되는 경우(예: lazy으로 정의되었거나 데이터를 가져오는 경우) renderToString은 해당 콘텐츠가 해결될 때까지 기다리지 않습니다. 대신 renderToString은 그 위에서 가장 가까운 <Suspense> 바운더리를 찾아 HTML에서 fallback prop을 렌더링합니다. 콘텐츠는 클라이언트 코드가 로드될 때까지 표시되지 않습니다.

To solve this, use one of the recommended streaming solutions. They can stream content in chunks as it resolves on the server so that the user sees the page being progressively filled in before the client code loads. 이 문제를 해결하려면 권장 스트리밍 솔루션 중 하나를 사용하세요. 이들은 서버에서 확인되는 대로 콘텐츠를 청크로 스트리밍하므로, 클라이언트 코드가 전부 로드되기 전에도 페이지가 점진적으로 채워지는 것을 볼 수 있습니다.