React Server Components 11 🧬 Context Providers — Rendering a Client Component provider from a Server tree
React Context is a client-side feature. It relies on createContext and useContext, both of which are hooks that run in the React client runtime. Server Components do not have a client runtime, so they cannot create or consume context directly. The solution is not to avoid context; it is to wrap the context provider in a Client Component, render that Client Component from the Server Component tree, and pass the Server Component’s children through the provider’s children slot.
This chapter covers the provider pattern: why createContext fails in a Server Component, the Providers Client Component that wraps the third-party or custom context, the root layout placement that makes the context available to every client component, and the bundle-size discipline of pushing the provider as deep as the tree allows.
Key point: A context provider is a Client Component. The Server Component renders it, and the provider’s children prop carries the server-rendered content through the client boundary. The provider’s state is client-side; the content it wraps can remain server-rendered.
Why context fails in a Server Component
The createContext error. The Next.js documentation states it directly: createContext only works in Client Components. A Server Component that calls createContext produces a build error with the message “createContext in a Server Component” . The function requires the client runtime’s context registry, which does not exist on the server.
The useContext error. The same constraint applies to consuming context. A Server Component that calls useContext is calling a hook, and hooks are client-only. The React documentation’s use API can read context, but the use call must be inside a component that the client runtime evaluates . A Server Component is not that component.
The third-party provider error. A third-party library like a theme provider or an auth provider is a Client Component internally, but if it is imported and rendered directly in a Server Component without the "use client" directive on the wrapper, the build fails. The Vercel guide explains that rendering a third-party context provider that does not have "use client" causes an error in Server Components . The fix is a local Client Component that wraps the provider and carries the directive.
a. The Providers Client Component
The pattern is a single file with "use client" at the top that imports the context providers and renders them with children.
// app/providers.tsx
'use client'
import { ThemeProvider } from 'next-themes'
import { AuthProvider } from './auth-context'
export function Providers({ children }: { children: React.ReactNode }) {
return (
<ThemeProvider attribute="class">
<AuthProvider>
{children}
</AuthProvider>
</ThemeProvider>
)
}
The Providers component is a Client Component. It imports the third-party and local providers, which are also client modules. The children prop is a React.ReactNode, and the Server Component passes the server-rendered content into it. The provider’s state—the theme, the auth session—lives in the client runtime. The content inside children was rendered on the server and is passed through as serialized JSX .
The Providers component does not need to know what the children are. It wraps them in the context providers and renders them. The Server Component that renders <Providers> does not need to know what the providers are. It passes its own children into the slot.
b. The root layout placement
The Providers component is rendered in the root layout, wrapping the {children} of the layout.
// app/layout.tsx
import { Providers } from './providers'
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en" suppressHydrationWarning>
<body>
<Providers>{children}</Providers>
</body>
</html>
)
}
The Vercel guide notes that the Providers component should wrap only {children}, not the entire <html> document . Wrapping the document would make the entire page a client subtree. Wrapping only {children} keeps the layout’s static parts—the <html>, the <body>, the metadata—as server-rendered, while the page content runs under the provider.
The suppressHydrationWarning attribute on <html> is a common companion when a theme provider sets a class on the document element before hydration. The mismatch between the server-rendered class and the client-set class would otherwise produce a hydration warning.
c. Pushing the provider down
The root layout is the convenient place for a provider that every route needs, such as a theme or an auth session. But a provider that only a subset of the tree needs should be placed lower, in the layout or page that requires it. The Next.js documentation’s composition guidance recommends moving Client Components down the tree to avoid unnecessarily increasing the client-side JavaScript bundle .
A dashboard route that needs a DashboardContext should render the provider in app/dashboard/layout.tsx, not in the root layout. The routes that do not use the dashboard context do not pay for its client bundle. The provider is still a Client Component, but its scope is limited to the segment that needs it.
The same principle applies to third-party providers. A QueryClientProvider for TanStack Query belongs in the layout of the routes that fetch data, not in the root layout of a static marketing site.
Complete Example Session
// ============================================
// PART 1: THE CUSTOM CONTEXT
// ============================================
// app/auth-context.tsx
'use client'
import { createContext, useContext, useState } from 'react'
const AuthContext = createContext<{ user: string | null }>({ user: null })
export function AuthProvider({ children }: { children: React.ReactNode }) {
const [user] = useState<string | null>('alice')
return <AuthContext.Provider value={{ user }}>{children}</AuthContext.Provider>
}
export function useAuth() {
return useContext(AuthContext)
}
// ============================================
// PART 2: THE PROVIDERS WRAPPER
// ============================================
// app/providers.tsx
'use client'
import { ThemeProvider } from 'next-themes'
import { AuthProvider } from './auth-context'
export function Providers({ children }: { children: React.ReactNode }) {
return (
<ThemeProvider attribute="class">
<AuthProvider>{children}</AuthProvider>
</ThemeProvider>
)
}
// ============================================
// PART 3: THE ROOT LAYOUT
// ============================================
// app/layout.tsx
import { Providers } from './providers'
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en" suppressHydrationWarning>
<body>
<Providers>{children}</Providers>
</body>
</html>
)
}
// ============================================
// PART 4: THE CONSUMER
// ============================================
// app/profile/page.tsx
'use client'
import { useAuth } from '../auth-context'
export default function ProfilePage() {
const { user } = useAuth()
return <p>Signed in as {user}</p>
}
// The page is a Client Component because it uses the hook.
// ============================================
// PART 5: THE SERVER CONTENT THROUGH THE SLOT
// ============================================
// app/page.tsx (Server Component)
import { Greeting } from './greeting' // Client Component
export default async function HomePage() {
const data = await getData()
return <Greeting name={data.name} />
}
// Greeting is a Client Component that can use the context.
// Its parent is a Server Component.
// ============================================
// PART 6: THE PROVIDER IN A SEGMENT LAYOUT
// ============================================
// app/dashboard/layout.tsx
'use client'
import { DashboardProvider } from './dashboard-context'
export default function DashboardLayout({ children }: { children: React.ReactNode }) {
return <DashboardProvider>{children}</DashboardProvider>
}
// Only the dashboard routes pay for this provider.
// ============================================
// PART 7: THE THIRD-PARTY PROVIDER
// ============================================
// app/providers.tsx
'use client'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { useState } from 'react'
export function Providers({ children }: { children: React.ReactNode }) {
const [client] = useState(() => new QueryClient())
return <QueryClientProvider client={client}>{children}</QueryClientProvider>
}
// The client is created once, not on every render.
// ============================================
// PART 8: THE NESTED PROVIDERS
// ============================================
'use client'
export function Providers({ children }: { children: React.ReactNode }) {
return (
<ThemeProvider>
<AuthProvider>
<QueryClientProvider client={client}>
{children}
</QueryClientProvider>
</AuthProvider>
</ThemeProvider>
)
}
// Order matters: inner providers can use outer context.
// ============================================
// PART 9: THE WRONG PLACEMENT
// ============================================
// app/layout.tsx
export default function RootLayout({ children }) {
return (
<html>
<body>
<Providers>
{children}
</Providers>
</body>
</html>
)
}
// Correct: Providers wraps {children}, not the whole document.
// ============================================
// PART 10: THE DECISION TREE
// ============================================
// Does the whole app need the context?
// Yes → root layout
//
// Does only a segment need it?
// Yes → segment layout
//
// Is it a third-party provider without "use client"?
// Yes → wrap it in a local Providers Client Component
The ten parts covered the custom context, the providers wrapper, the root layout, the consumer, the server content through the slot, the segment layout, the third-party provider, the nested providers, the wrong placement, and the decision tree.
Quick Reference
The provider pattern
| Step | File | Directive |
|---|---|---|
| Define context | auth-context.tsx | 'use client' |
| Wrap providers | providers.tsx | 'use client' |
| Render provider | layout.tsx | None (Server Component) |
| Consume context | page.tsx or component | 'use client' |
Provider placement
| Scope | Location |
|---|---|
| Entire app | app/layout.tsx |
| One segment | app/<segment>/layout.tsx |
| One route group | app/(group)/layout.tsx |
Common errors
| Error | Cause | Fix |
|---|---|---|
createContext in Server Component | No "use client" | Add the directive to the context file |
| Third-party provider error | Provider lacks "use client" | Wrap it in a local Client Component |
Provider wraps <html> | Placement too high | Wrap only {children} |
Best Practices
✅ Do This:
// Put "use client" at the top of the providers file
'use client' // ✅
// Wrap only the children
<Providers>{children}</Providers> // ✅
// Push segment-specific providers down
<DashboardProvider>{children}</DashboardProvider> // ✅
// Create the QueryClient once with useState
const [client] = useState(() => new QueryClient()) // ✅
❌ Don’t Do This:
// Call createContext in a Server Component
const Ctx = createContext() // ❌
// Render a third-party provider without a client wrapper
<ThemeProvider>{children}</ThemeProvider> // ❌
// Wrap the entire <html> in the provider
<Providers><html>...</html></Providers> // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
Build error on createContext | Server Component | Add "use client" to the context file |
| Hydration warning on theme | Theme class set before hydration | Add suppressHydrationWarning to <html> |
| Provider state resets | Provider defined inside a Server Component render | Define it in a Client Component |
Context is undefined in a consumer | Consumer is outside the provider | Move the consumer inside the provider |
| Bundle includes provider everywhere | Provider in root layout for a segment-only need | Move it to the segment layout |
Real-World Examples
1. Custom context
'use client'
const AuthContext = createContext({ user: null })
2. Providers wrapper
'use client'
export function Providers({ children }) {
return <AuthProvider>{children}</AuthProvider>
}
3. Root layout
<Providers>{children}</Providers>
4. Consumer
'use client'
const { user } = useAuth()
5. Third-party theme provider
<ThemeProvider attribute="class">{children}</ThemeProvider>
6. QueryClient provider
const [client] = useState(() => new QueryClient())
7. Segment provider
// app/dashboard/layout.tsx
'use client'
<DashboardProvider>{children}</DashboardProvider>
8. Hydration warning
<html suppressHydrationWarning>
9. The error
createContext only works in Client Components.
10. The decision
App-wide? → root layout
Segment? → segment layout
Third-party? → local wrapper
Visual
The provider boundary
┌─────────────────────────────────────────────────────────────┐
│ Server Component (layout.tsx) │
│ │ │
│ ▼ │
│ <Providers> ← Client Component │
│ │ │
│ ├── ThemeProvider (client) │
│ │ └── AuthProvider (client) │
│ │ └── {children} ← server-rendered JSX │
│ │ │
│ ▼ │
│ Client Component consumers can use the context │
└─────────────────────────────────────────────────────────────┘
The wrong placement
┌─────────────────────────────────────────────────────────────┐
│ WRONG: │
│ <Providers> │
│ <html>...</html> │
│ </Providers> │
│ → the whole document is a client subtree │
│ │
│ RIGHT: │
│ <html> │
│ <body> │
│ <Providers>{children}</Providers> │
│ </body> │
│ </html> │
│ → only the page content is under the provider │
└─────────────────────────────────────────────────────────────┘
The children slot
┌─────────────────────────────────────────────────────────────┐
│ Server Component renders <Providers>{children}</Providers> │
│ │ │
│ ▼ │
│ Providers receives the server-rendered JSX as children │
│ │ │
│ ▼ │
│ Providers wraps it in the context providers │
│ │ │
│ ▼ │
│ The client consumers inside can read the context │
└─────────────────────────────────────────────────────────────┘
The placement decision
┌─────────────────────────────────────────────────────────────┐
│ App-wide context? │
│ └── root layout │
│ │
│ Segment context? │
│ └── segment layout │
│ │
│ Third-party without "use client"? │
│ └── local Providers Client Component │
└─────────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Context creation | createContext in a "use client" file |
| Provider wrapper | "use client" file that renders the providers |
| Root placement | app/layout.tsx, wrapping {children} |
| Segment placement | app/<segment>/layout.tsx |
| Consumer | A Client Component that calls the hook |
| Server content | Passed through the provider’s children slot |
| Hydration warning fix | suppressHydrationWarning on <html> |
Key takeaways:
- Context is a client-side feature.
createContextanduseContextrequire the client runtime. A Server Component that calls either produces a build error. The context must live in a"use client"file . - The provider is a Client Component that wraps the context. The
Providersfile carries"use client", imports the context providers, and renders them withchildren. The Server Component renders<Providers>and passes its own children into the slot . - The root layout is the default placement for app-wide context. The
Providerscomponent wraps{children}inside the<body>, not the entire<html>document. Wrapping only the children keeps the static layout parts server-rendered . - Segment-specific context belongs in the segment layout. A provider that only the dashboard routes need should be in
app/dashboard/layout.tsx, not the root layout. The routes that do not use the context do not pay for its client bundle . - Third-party providers need a local client wrapper. A library’s provider may not have
"use client"at its entry point, and rendering it directly in a Server Component fails. The localProvidersClient Component wraps it and carries the directive . - The children slot carries server-rendered content through the client boundary. The provider’s state is client-side, but the content inside
childrenwas rendered on the server and is passed as serialized JSX. The provider does not need to know what the content is.
Remember: Context is a client tool. The Server Component cannot create it or consume it, but it can render a Client Component that provides it. The Providers file is that Client Component. It carries "use client", it wraps the third-party and custom context providers, and it renders the server-rendered children inside them. Place it in the root layout for app-wide context, in a segment layout for scoped context, and always wrap only the children, not the document. The result is a tree where the layout and static content stay on the server, and the client consumers have the context they need.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!