Server Components

Server Components

React Server Components와 함께 Chakra UI를 사용하는 방법을 다루는 개념 문서예요.

출처: 문서

본문

React Server Components는 React의 새로운 기능으로, 서버에서 렌더링되고 hydration 없이 UI를 클라이언트에 반환하는 컴포넌트를 만들 수 있게 해 줘요.

클라이언트 컴포넌트는 여전히 서버 렌더링되지만 클라이언트에서 hydration돼요. Server component 패턴에 대해 더 알아보세요.

Chakra UI 컴포넌트는 서버 컴포넌트에서 사용할 수 없는 useState, useRef, useContext에 의존하기 때문에 클라이언트 컴포넌트예요.

:::info

TLDR: 기본적으로 Chakra UI 컴포넌트는 'use client' 지시자를 추가하지 않고도 React Server Components와 함께 사용할 수 있어요.

:::

사용법 (Usage)

다음은 Next.js에서 Chakra UI 컴포넌트를 React Server Components와 함께 사용하는 예시예요.

import { Heading } from "@chakra-ui/react"
import fs from "node:fs"

export default async function Page() {
  const content = fs.readFileSync("path/to/file.md", "utf-8")
  return <Heading as="h1">{content}</Heading>
}

Chakra Factory

chakra() 팩토리 함수를 사용할 때는 use client 지시자를 사용하고 컴포넌트를 전용 파일로 옮겨 주세요.

"use client"

import { chakra } from "@chakra-ui/react"

export const BlogPost = chakra("div", {
  base: {
    color: "red",
  },
  variants: {
    primary: {
      true: { color: "blue" },
      false: { color: "green" },
    },
  },
})

그런 다음 페이지 서버 컴포넌트에서 컴포넌트를 import해요.

import { BlogPost } from "./blog-post"

export default async function Page() {
  const content = fs.readFileSync("path/to/file.md", "utf-8")
  return <BlogPost>{content}</BlogPost>
}

훅 (Hooks)

Chakra UI에서 훅을 import할 때는 use client 지시자를 사용해 주세요.

"use client"

import { useBreakpointValue } from "@chakra-ui/react"

export function MyComponent() {
  const value = useBreakpointValue({ base: "mobile", md: "desktop" })
  return <div>{value}</div>
}

Render Props

render props를 사용할 때는 use client 지시자를 사용해 주세요.

"use client"

import { ProgressContext } from "@chakra-ui/react"

export function MyComponent() {
  return <ProgressContext>{({ value }) => <div>{value}</div>}</ProgressContext>
}

더 알아보기 (Learn more)

Chakra UI를 React Server Components와 함께 사용하는 더 자세한 내용은 공식 문서를 확인해 보세요.