CodePark/ questions / Server & Client Components
START PRACTICINGPRACTICE
Frontend question · Next.js › Server & Client Components

How do you use React Context (for a theme or auth provider) in the App Router?

// app/theme-provider.tsx
"use client";
import { createContext } from "react";
export const ThemeContext = createContext("light");

export default function ThemeProvider({ children }: { children: React.ReactNode }) {
  return <ThemeContext.Provider value="dark">{children}</ThemeContext.Provider>;
}

// app/layout.tsx (Server Component)
// <body><ThemeProvider>{children}</ThemeProvider></body>

Put the context provider in its own Client Component, and wrap children with it in the root layout.

Server Components cannot create or read React Context. So the provider must be a Client Component. Create a small file that starts with "use client". It renders the context provider and accepts children.

The root layout stays a Server Component and wraps its children with that provider. The pages arrive as children, so they stay Server Components. Only components that call useContext need to be Client Components.

Render the provider as deep in the tree as you can. This keeps more of the tree static. That makes it easier for Next.js to optimize the static parts.

  • Server Components cannot use React Context.
  • Put the provider in its own "use client" file.
  • Wrap children with the provider in the layout, so pages stay Server Components.
  • Only components that read the context need to be Client Components.