Next.js 13에서 Contexts 사용하기

Sooo·2023년 8월 13일
1

Next.js

목록 보기
1/4

원 글 NextJs에서 contexts를 사용하면 앱 전체가 클라이언트에서 렌더링될까? 부분 번역

React Context를 서버 컴포넌트에서 사용할 수 있을까?

  • 서버 컴포넌트에서는 Context 사용 불가
  • Context Provider를 제공하면, 그 컴포넌트 자식 트리의 클라이언트 컴포넌트들은 모두 해당 컨텍스트 사용 가능
    • 자식 트리 중 서버 컴포넌트들은 컨텍스트에 영향 받지 않음

NextJS 원칙들

  1. NextJs의 RootLayout은 항상 서버 컴포넌트이다
  2. RootLayout에 전달된 자식 prop또한 서버컴포넌트이다
  3. 서버 컴포넌트들은 클라이언트 컴포넌트들을 포함할 수 있다(클라이언트 컴포넌트들은 서버 컴포넌트들이 서버에서 렌더링될 때 무시된다)
  4. 서버 컴포넌트들은 클라이언트 컴포넌트들에게 자식으로 전달된다면, 포함될 수 있다
/*
	NextJs에서 어떻게 contexts를 세팅하는가 예시
	https://dev.to/perssondennis/do-contexts-in-nextjs-13-make-the-whole-app-render-on-the-client-55bb#:~:text=Next.js%20guide%20for%20how%20to%20set%20up%20contexts
*/

import { ContextProviders } from './providers';

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <ContextProviders>{children}</ContextProviders>
      </body>
    </html>
  );
}
  • 위의 #1에 의해, Root Layout은 서버 컴포넌트이다
  • contexts를 포함하는 ContextProviders 컴포넌트는 클라이언트 컴포넌트이다 (#3를 만족함)
  • RootLayout의 자식 prop은 서버 컴포넌트이다 (#2)
  • children은 ContextProviders 클라이언트 컴포넌트로 전달된다 (#4를 만족함)
    • children은 서버 컴포넌트, 클라이언트 컴포넌트 모두 가능함

따라서 위의 코드는 아래와 같은 리액트 트리 구조를 가진다

<RootLayout (Server Component)>
  <ContextProviders (Client Component)>
    <Page (Server Component)>
      <Potential other Client Components using the context />
      <Potential other Server Components ignoring the context />
    </Page>
  </ContextProviders>
</RootLayout>

1개의 댓글

comment-user-thumbnail
2023년 8월 13일

좋은 글 감사합니다. 자주 올게요 :)

답글 달기