Server Components는 번들링 이전에 클라이언트 앱, SSR 서버와 별도의 환경에서 미리 렌더링 되는 새로운 컴포넌트입니다.
별도의 환경은 React Server Components의 Server를 의미합니다. Server Components는 CI 서버에서 빌드 시 한 번 실행 될 수도 있고, 웹 서버를 사용하여 각 요청에 대해 매 번 실행 될 수도 있습니다.
server components 적용 전
// bundle.js
import marked from 'marked'; // 35.9K (11.2K gzipped)
import sanitizeHtml from 'sanitize-html'; // 206K (63.3K gzipped)
function Page({page}) {
const [content, setContent] = useState('');
// NOTE: loads *after* first page render.
useEffect(() => {
fetch(`/api/content/${page}`).then((data) => {
setContent(data.content);
});
}, [page]);
return <div>{sanitizeHtml(marked(content))}</div>;
}
// api.js
app.get(`/api/content/:page`, async (req, res) => {
const page = req.params.page;
const content = await file.readFile(`${page}.md`);
res.send({content});
});
이 패턴은 사용자가 추가로 75K(gzip)의 라이브러리를 다운로드하고 구문 분석하고 페이지가 로드된 후 데이터를 가져오는 두 번째 요청을 기다려야 함을 의미합니다. 이는 페이지의 수명 동안 변경되지 않는 정적 콘텐츠를 렌더링하기 위해서입니다.
Server Components 적용
// bundle.js
import marked from 'marked'; // Not included in bundle
import sanitizeHtml from 'sanitize-html'; // Not included in bundle
async function Page({page}) {
// NOTE: loads *during* render, when the app is built.
const content = await file.readFile(`${page}.md`);
return <div>{sanitizeHtml(marked(content))}</div>;
}
렌더링된 출력은 HTML로 서버 측 렌더링(SSR)되어 CDN에 업로드될 수 있습니다. 앱이 로드되면 클라이언트는 원래 Page
구성 요소나 마크다운을 렌더링하는 데 드는 비용이 많이 드는 라이브러리를 볼 수 없습니다. 클라이언트는 렌더링된 출력만 볼 수 있습니다.
즉, 첫 번째 페이지가 로드되는 동안 콘텐츠가 표시되고, 번들에는 정적 콘텐츠를 렌더링하는 데 필요한 값비싼 라이브러리가 포함되지 않습니다.
Server Components는 페이지 요청 중에 웹 서버에서 실행될 수 있어 API를 구축하지 않고도 데이터 레이어에 액세스할 수 있습니다. 이들은 애플리케이션이 번들되기 전에 렌더링되며, 데이터와 JSX를 Client Components에 props로 전달할 수 있습니다.