renderToStaticMarkup

renderToStaticMarkup ์ƒํ˜ธ์ž‘์šฉํ•˜์ง€ ์•Š๋Š” React ํŠธ๋ฆฌ๋ฅผ HTML ๋ฌธ์ž์—ด๋กœ ๋ Œ๋”๋งํ•ฉ๋‹ˆ๋‹ค.

const html = renderToStaticMarkup(reactNode)

์ฐธ์กฐ

renderToStaticMarkup(reactNode)

์„œ๋ฒ„์—์„œ renderToStaticMarkup์„ ํ˜ธ์ถœํ•˜์—ฌ ์•ฑ์„ HTML๋กœ ๋ Œ๋”๋งํ•ฉ๋‹ˆ๋‹ค.

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

const html = renderToStaticMarkup(<Page />);

์ƒํ˜ธ์ž‘์šฉํ•˜์ง€ ์•Š๋Š” React ์ปดํฌ๋„ŒํŠธ์˜ HTML ์ถœ๋ ฅ์„ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.

์•„๋ž˜ ์˜ˆ์‹œ๋ฅผ ์ฐธ๊ณ ํ•˜์„ธ์š”.

ํŒŒ๋ผ๋ฏธํ„ฐ

  • reactNode: HTML๋กœ ๋ Œ๋”๋งํ•  React ๋…ธ๋“œ์ž…๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, <Page />์™€ ๊ฐ™์€ JSX ๋…ธ๋“œ์ž…๋‹ˆ๋‹ค.

๋ฐ˜ํ™˜

HTML ๋ฌธ์ž์—ด์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

์ฃผ์˜ ์‚ฌํ•ญ

  • renderToStaticMarkup์˜ ์ถœ๋ ฅ๊ฐ’์€ hydrate ๋  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.

  • renderToStaticMarkup์€ Suspense๋ฅผ ์ œํ•œ์ ์œผ๋กœ ์ง€์›ํ•ฉ๋‹ˆ๋‹ค. ๋งŒ์•ฝ suspense ์ปดํฌ๋„ŒํŠธ๋ผ๋ฉด, renderToStaticMarkup์€ ์ฆ‰์‹œ HTML์„ fallback์œผ๋กœ ๋ณด๋ƒ…๋‹ˆ๋‹ค.

  • renderToStaticMarkup์€ ๋ธŒ๋ผ์šฐ์ €์—์„œ ๋™์ž‘ํ•˜์ง€๋งŒ, ํด๋ผ์ด์–ธํŠธ ์ฝ”๋“œ์—์„œ ์‚ฌ์šฉ๋˜๋Š” ๊ฑด ๊ถŒ์žฅํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๋ธŒ๋ผ์šฐ์ €์—์„œ ์ปดํฌ๋„ŒํŠธ๋ฅผ HTML๋กœ ๋ Œ๋”๋งํ•ด์•ผ ํ•˜๋Š” ๊ฒฝ์šฐ, HTML ์„ DOM ๋…ธ๋“œ๋กœ ๋ Œ๋”๋งํ•ด์„œ ๊ฐ€์ ธ์˜ค์„ธ์š”.


์‚ฌ์šฉ๋ฒ•

์ƒํ˜ธ์ž‘์šฉํ•˜์ง€ ์•Š๋Š” React ํŠธ๋ฆฌ๋ฅผ HTML ๋ฌธ์ž์—ด๋กœ ๋ Œ๋”๋งํ•˜๊ธฐ

renderToStaticMarkup์„ ์„œ๋ฒ„ ์‘๋‹ต๊ณผ ํ•จ๊ป˜ ๋ณด๋‚ผ ์ˆ˜ ์žˆ๋Š” HTML ๋ฌธ์ž์—ด๋กœ ์•ฑ์— ๋ Œ๋”๋งํ•˜๊ธฐ ์œ„ํ•ด ํ˜ธ์ถœํ•˜์„ธ์š”:

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

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

์ด๊ฒƒ์€ React ์ปดํฌ๋„ŒํŠธ์˜ ์ƒํ˜ธ์ž‘์šฉํ•˜์ง€ ์•Š๋Š” ์ดˆ๊ธฐ HTML ๊ฒฐ๊ณผ๊ฐ€ ์ƒ์„ฑ๋ฉ๋‹ˆ๋‹ค.

์ฃผ์˜ํ•˜์„ธ์š”!

์ด ๋ฉ”์„œ๋“œ๋Š” hydrate ๋  ์ˆ˜ ์—†๊ณ  ์ƒํ˜ธ์ž‘์šฉํ•˜์ง€ ์•Š๋Š” HTML ์„ ๋ Œ๋”๋งํ•ฉ๋‹ˆ๋‹ค. ์ด ๋ฉ”์„œ๋“œ๋Š” React๋ฅผ ๊ฐ„๋‹จํ•œ ์ •์  ํŽ˜์ด์ง€ ์ƒ์„ฑ๊ธฐ๋กœ ์‚ฌ์šฉํ•˜๊ฑฐ๋‚˜ ์ด๋ฉ”์ผ๊ณผ ๊ฐ™์€ ์™„์ „ํžˆ ์ •์ ์ธ ์ฝ˜ํ…์ธ ๋ฅผ ๋ Œ๋”๋งํ•  ๋•Œ ์œ ์šฉํ•ฉ๋‹ˆ๋‹ค.

์ƒํ˜ธ์ž‘์šฉ์„ ์œ„ํ•œ ์•ฑ์€ ์„œ๋ฒ„์—์„œ renderToString์„, ํด๋ผ์ด์–ธํŠธ์—์„œ hydrateRoot๋ฅผ ์‚ฌ์šฉํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.