Back to Chakra Ui

Server Components

apps/www/content/docs/components/concepts/server-components.mdx

0.3.0-beta2.2 KB
Original Source

React Server Components is a new feature in React that allows you to build components that render on the server and return UI to the client without hydration.

Client components are still server-rendered but hydrated on the client. Learn more about Server component patterns

Chakra UI components are client components because they rely on useState, useRef and useContext which are not available in server components.

:::info

TLDR: By default, Chakra UI components can be used with React Server Components without adding the 'use client' directive.

:::

Usage

Here's an example of how to use Chakra UI components with React Server Components in Next.js

jsx
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

When using the chakra() factory function, use the use client directive and move the component to a dedicated file.

jsx
"use client"

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

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

Then import the component in your page server component

jsx
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

When importing hooks from Chakra UI, use the use client directive

jsx
"use client"

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

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

Render Props

When using render props, use the use client directive

jsx
"use client"

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

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