renderToStaticNodeStream

Chaerin Kim·2023년 12월 21일

renderToStaticNodeStream은 비대화형 React 트리를 Node.js Readable Stream으로 렌더링함.

const stream = renderToStaticNodeStream(reactNode)

Reference

renderToStaticNodeStream(reactNode)

서버에서 renderToStaticNodeStream을 호출하여 Node.js Readable Stream로 렌더링할 수 있음.

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

const stream = renderToStaticNodeStream(<Page />);
stream.pipe(response);

Stream은 React 컴포넌트의 비대화형 HTML 출력을 생성함.

Parameters

  • reactNode: HTML로 렌더링하려는 React 노드. 예를 들어, <Page />와 같은 JSX 노드.
  • options (optional): 서버 렌더링을 위한 객체.
    • identifierPrefix (optional): React가 useId에 의해 생성된 ID에 사용하는 문자열 접두사. 같은 페이지에서 여러 루트를 사용할 때 충돌을 피하는 데 유용함.

Returns

HTML 문자열을 출력하는 Node.js Readable Stream을 반환함. 결과 HTML은 클라이언트에서 hydrate 할 수 없음.

Caveats

  • renderToStaticNodeStream 출력을 hydrate 할 수 없음.

  • 이 메서드는 출력을 반환하기 전에 모든 Suspense boundary가 완료될 때까지 기다림.

  • React 18부터 이 메서드는 모든 출력을 버퍼링하므로 실제로는 스트리밍 이점을 제공하지 않음.

  • 반환되는 스트림은 utf-8로 인코딩된 바이트 스트림임. 다른 인코딩의 스트림이 필요한 경우, 텍스트 트랜스코딩을 위한 트랜스폼 스트림을 제공하는 iconv-lite와 같은 프로젝트를 살펴볼 것.


Usage

Rendering a React tree as static HTML to a Node.js Readable Stream

renderToStaticNodeStream을 호출하여 서버 응답으로 파이프할 수 있는 Node.js Readable Stream을 생성할 수 있음:

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

// The route handler syntax depends on your backend framework
app.use('/', (request, response) => {
  const stream = renderToStaticNodeStream(<Page />);
  stream.pipe(response);
});

스트림은 React 컴포넌트의 초기 비대화형 HTML 출력을 생성함.

Pitfall

이 메서드는 hydrate될 수 없는 비대화형 HTML을 렌더링함. 이 메서드는 React를 간단한 정적 페이지 생성기로 사용하거나 이메일과 같이 완전히 정적인 콘텐츠를 렌더링할 때 유용함.

인터랙티브 앱은 서버에서 renderToString을 사용하고 클라이언트에서 hydrateRoot를 사용해야 함.

0개의 댓글