Passing props works well between a component and its direct children. When the same value matters to pieces scattered across the whole tree, an SPA reaches for context or a global store. With Server Components, neither behaves the way you're used to: context doesn't exist on the server, and a module variable is shared between different visitors.
In this lesson you'll learn to place client providers without converting the whole application, you'll build a light or dark theme switcher that doesn't flicker or break hydration, you'll see how to share data within a request on the server and why user state must not be stored in a module. You'll finish by integrating libraries that don't ship the directive.
- Context lives on the client
A Server Component can't create or read context. You already know why: there's no instance that updates when the value changes. But a provider is a wrapper with a slot, and client wrappers accept server children.
'use client'
import { createContext } from 'react'
export const LanguageContext = createContext('en')
export function LanguageProvider({ children }: { children: React.ReactNode }) {
return <LanguageContext value="en">{children}</LanguageContext>
}Since React 19 the context itself is used as the provider, without .Provider. Placed in a layout, whatever is inside it remains server code, because the owner of that JSX is the layout. Client Components that appear further down, even inside Server Components, can read the value.
flowchart TD
L["RootLayout (server)"] --> P["ThemeProvider (CLIENT)"]
P -- "children" --> LP["PublicLayout (server)"]
LP --> C["Header (server)"]
C --> S["ThemeSelect (CLIENT)<br/>reads the context"]
LP --> PE["EventsPage (server)<br/>can't read it"]
Three recommendations before you write one:
- Place it as low as you can. If only the dashboard uses it, it goes in
DashboardLayout. In the root, wrap{children}and not the whole<html>, so that Next.js can optimize the static parts. - Ask whether you need it. Favorites are shared between components without context, with
useSyncExternalStore. Filters are shared through the URL. And server data that several Server Components need doesn't go through context (section 4). - One provider per concern. One that groups theme, user and notices re-renders all its readers whenever any of them changes.
- A light or dark theme
Visitors will be able to choose between "System", "Light" and "Dark", and the choice will be remembered in localStorage. The problem is one of ordering: the server prerenders the HTML without knowing what they chose. These are the usual approaches and their flaw:
| Approach | Flaw |
|---|---|
useState that reads localStorage |
Hydration error |
useEffect that applies the theme on mount |
Flicker: you see light and then dark |
useLayoutEffect |
It runs before painting, but after hydrating; on a slow network the flicker remains |
A cookie read with cookies() in the root layout |
Makes every page depend on the request |
An inline script in the <head> |
None of the above |
The last one is what the documentation recommends. An inline script runs while the browser is reading the HTML, before the first paint and before React exists. It sets an attribute on <html> and CSS does the rest.
2.1. What both sides share
// lib/theme.ts
export const THEME_KEY = 'agendaviva:theme'
export const THEME_PREFERENCES = ['system', 'light', 'dark'] as const
export type ThemePreference = (typeof THEME_PREFERENCES)[number]
export function isThemePreference(value: unknown): value is ThemePreference {
return THEME_PREFERENCES.some((preference) => preference === value)
}
// Runs in the browser before painting: classic, self-contained JavaScript
export const THEME_SCRIPT = `(function () {
var saved = null
try { saved = localStorage.getItem('${THEME_KEY}') } catch (e) {}
var systemDark = matchMedia('(prefers-color-scheme: dark)').matches
var dark = saved === 'dark' || (saved !== 'light' && systemDark)
document.documentElement.setAttribute('data-theme', dark ? 'dark' : 'light')
})()`The module has no directive because both sides use it: the layout needs THEME_SCRIPT and the provider, the rest. If it were in a file with 'use client', the layout would receive a reference instead of the text, as you saw in 03-03.
The script is constant text, with no user data. That matters, because it will be inserted without escaping.
2.2. The layout and the CSS
// app/layout.tsx (RootLayout; imports ThemeProvider and THEME_SCRIPT)
export default function RootLayout({ children }: LayoutProps<'/'>) {
return (
<html lang="en" suppressHydrationWarning>
<head>
<script dangerouslySetInnerHTML={{ __html: THEME_SCRIPT }} />
</head>
<body className="flex min-h-screen flex-col bg-slate-50 text-slate-900 dark:bg-slate-950 dark:text-slate-100">
<ThemeProvider>{children}</ThemeProvider>
</body>
</html>
)
}/* app/globals.css */
@import "tailwindcss";
@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *));
[data-theme='dark'] {
color-scheme: dark;
}suppressHydrationWarningon<html>: the script adds an attribute React didn't set, and that's intentional. It only affects that element; hydration errors in the rest are still reported.@custom-variant darkmakes Tailwind'sdark:variant depend on our attribute rather than on the system preference.color-scheme: darktells the browser to adapt form fields, scrollbars and the modal's<dialog>.
To keep it readable, add dark:bg-slate-900 dark:border-slate-700 to the header and to the event and venue cards, and dark:text-slate-300 to their secondary text. The look and feel will be polished in 09-01. Once there's a CSP policy (08-05), the script will need explicit permission.
In development, React may show a warning about <script> tags rendered in the browser. The documentation offers an alternative that avoids it, inserting the script with the useServerInsertedHTML hook; the version in the layout is enough to understand the mechanism.
2.3. The provider
// components/theme-provider.tsx
'use client'
import { createContext, use, useLayoutEffect, useSyncExternalStore } from 'react'
import { THEME_KEY, isThemePreference, type ThemePreference } from '@/lib/theme'
interface ThemeValue {
preference: ThemePreference
setPreference: (next: ThemePreference) => void
}
const ThemeContext = createContext<ThemeValue | null>(null)
const listeners = new Set<() => void>()
function subscribe(onChange: () => void): () => void {
listeners.add(onChange)
window.addEventListener('storage', onChange)
return () => {
listeners.delete(onChange)
window.removeEventListener('storage', onChange)
}
}
function readPreference(): ThemePreference {
try {
const saved = localStorage.getItem(THEME_KEY)
return isThemePreference(saved) ? saved : 'system'
} catch {
return 'system'
}
}
function readOnServer(): ThemePreference {
return 'system'
}
function applyTheme(preference: ThemePreference): void {
const systemDark = matchMedia('(prefers-color-scheme: dark)').matches
const dark = preference === 'dark' || (preference === 'system' && systemDark)
document.documentElement.setAttribute('data-theme', dark ? 'dark' : 'light')
}
function setPreference(next: ThemePreference): void {
try {
localStorage.setItem(THEME_KEY, next)
} catch {
return
}
listeners.forEach((notify) => notify())
}
export function ThemeProvider({ children }: { children: React.ReactNode }) {
const preference = useSyncExternalStore(subscribe, readPreference, readOnServer)
useLayoutEffect(() => {
applyTheme(readPreference())
}, [preference])
return (
<ThemeContext value={{ preference, setPreference }}>{children}</ThemeContext>
)
}
export function useTheme(): ThemeValue {
const value = use(ThemeContext)
if (!value) throw new Error('useTheme must be used within ThemeProvider')
return value
}It's the favorites pattern, with three new details:
- The effect reads the stored preference again, instead of using the
preferencevariable. During hydration that variable is'system'; applying it would momentarily undo what the script did. - The effect looks redundant, but it isn't. It applies later changes, including those coming from another tab. And in development, React's strict mode remounts components and leaves only the JSX attributes on
<html>, which removes the script's attribute; here it's restored. - The context value is a new object on every render, and even so it doesn't cause extra renders.
ThemeProvideronly renders when the preference changes, because whatever contains it is a server component andchildrenarrives ready-made.
// components/theme-select.tsx
'use client'
import { useTheme } from '@/components/theme-provider'
import { isThemePreference } from '@/lib/theme'
export function ThemeSelect() {
const { preference, setPreference } = useTheme()
return (
<select
aria-label="Color theme"
value={preference}
onChange={({ target }) => {
if (isThemePreference(target.value)) setPreference(target.value)
}}
>
<option value="system">System</option>
<option value="light">Light</option>
<option value="dark">Dark</option>
</select>
)
}Place it in Header, after the favorites counter, and in the ManagementLayout bar. They're two different trees and neither receives props for it: that's what context brings. useTheme throws an error if the provider is missing, so that an oversight gets noticed early.
Reload in dark mode with network throttling: the colors are right from the very first moment. The dropdown does show "System" until it hydrates, because that's the server value. If that bothered you, the fix is the one from 03-02: use(browser()) with a same-sized placeholder as the fallback.
In a real project you can use the next-themes library, which applies this same technique. Writing it once helps you understand why it asks for suppressHydrationWarning on <html>.
- Server data in a context
The theme originates in the browser. Other values originate on the server and many Client Components read them: the user, their permissions, translations. There are two ways to put them into a context.
// 1. Wait for the value: blocks everything below
const user = await getUser()
<UserProvider user={user}>{children}</UserProvider>
// 2. Hand over the promise: each reader decides on its <Suspense>
const user = getUser()
<UserProvider user={user}>{children}</UserProvider>With the second, the reader does use(use(UserContext)): the first gets the promise and the second, its value. It's the one to use in a layout, where an await outside a <Suspense> would also be an error with Cache Components.
Two caveats. Everything you put in that context is public to that visitor, like any prop that crosses: pass the name and role, not the record. And to refresh the value you have to re-render the Server Component that created it, so don't place it higher than necessary. AgendaViva won't have a user until module 8.
- Sharing on the server: React.cache
There's no context between Server Components, and you'll rarely miss it. If two components need the same event, both ask for it. That's clearer than passing it down through five levels, and each one stays independent.
The objection is the repeated query. That's what React's cache is for: it wraps a function and remembers its result for a single request.
import { cache } from 'react'
export const getEventBySlug = cache(
async (slug: string): Promise<AgendaEvent | null> => {
await simulateQuery()
// … same query as before
},
)If a page and two components call it with 'jazz-night' in the same request, the query runs once and all three receive the same promise. For the next request the memory is empty.
React.cache |
'use cache' (module 5) |
|
|---|---|---|
| Duration | One request | Whatever you specify |
| Shared between visitors | No | Yes, except for its private variant |
| What it's for | Not repeating work within a render | Not repeating queries across requests |
Two rules: it's called outside components, at module level, because each call to cache creates a new memory; and arguments are compared by identity, so an object literal never gets a hit. This is an introduction. In 04-03 we'll apply it to the data layer to avoid repetition and to preload.
- Why there's no global state on the server
In the browser, a module variable belongs to one visitor: it's their tab. On the server, the module is loaded once and serves everyone. This code works perfectly on your machine:
// Dangerous: shared between all requests
let currentUser: User | null = null
export function setCurrentUser(user: User) {
currentUser = user
}
export function getCurrentUser() {
return currentUser
}sequenceDiagram
participant A as Ana's request
participant M as Module variable
participant B as Bruno's request
A->>M: setCurrentUser(Ana)
A->>A: waits for a query
B->>M: setCurrentUser(Bruno)
A->>M: getCurrentUser()
M-->>A: Bruno
Note over A: Ana sees Bruno's bookings
The requests don't need to run in parallel: a single await between writing and reading is enough. It's a serious bug, because it leaks personal data, and almost impossible to reproduce with a single user testing.
It wouldn't work for the opposite either, deliberate sharing. With several instances of the application each one would have its own copy, and it would be lost on deployment. Apply it like this:
| State | Where it goes |
|---|---|
| User and session | A cookie, read on every request (04-05, 08-01) |
| A half-finished booking | Form, URL or database |
| Preferences without an account | localStorage or a cookie |
| Data shared between visitors | Database or 'use cache' |
| Constants, formatters, connections | A module variable: they don't depend on the visitor |
The last row makes it clear that module variables aren't forbidden. dateTimeFormat, in lib/format.ts, is fine: it's created once and doesn't store anything about anyone. And so is listeners, in lib/favorites.ts: the module is evaluated during prerendering, but it's only written to from subscriptions, which don't happen on the server.
Global state libraries (Zustand, Redux, Jotai…) fall into the same trap if the store is created at module level, because Client Components also run on the server. The remedy is to create the store inside a provider, once per tree:
'use client'
export function StoreProvider({ children }: { children: React.ReactNode }) {
const [store] = useState(() => createStore())
return <StoreContext value={store}>{children}</StoreContext>
}Before adding one, check what's left to store. With data on the server, filters in the URL and mutations in Server Actions, AgendaViva doesn't need any.
- Third-party libraries
Many component libraries use state or effects. If their code has 'use client', they can be imported from anywhere. If not, using them in a Server Component triggers the error from 03-01, inside node_modules and with no way for you to edit it.
The fix is to set the boundary yourself. With a fictional example-carousel package:
Now Server Components import Carousel from @/components/carousel. This layer has another advantage: the library is named in a single file, and replacing it or setting its options doesn't affect the pages. If its props include functions, the wrapper is the place to define them, because they couldn't arrive from the server:
// components/event-carousel.tsx
'use client'
import { Carousel } from 'example-carousel'
export function EventCarousel({ children }: { children: React.ReactNode }) {
return (
<Carousel onChange={(index: number) => console.log('Slide', index)}>
{children}
</Carousel>
)
}| Symptom | Cause | Fix |
|---|---|---|
A useState error in a Server Component |
The library is missing the directive | A wrapper module |
Element type is invalid with Menu.Item |
A compound component across the boundary | Use it whole inside a Client Component of your own |
window is not defined on import |
It accesses the browser when loaded | next/dynamic with ssr: false, in a Client Component (10-02) |
| Hydration error | It generates identifiers or measures during render | Update it or use(browser()) |
| "Context not found" | Its provider is missing | Add it in the layout that needs it |
And the other way round: libraries that only transform data (dates, Markdown, validation) don't need a boundary. Leave them on the server and they'll cost the visitor nothing.
When there are several providers in the root layout, group them in a client components/providers.tsx that nests them. With only one, as now, it would be an empty layer.
Common Mistakes and Tips
- Marking
RootLayoutwith'use client'to use a provider. You'd losemetadataand drag everything it imports into the client. Extract the provider. - Reading context in a Server Component. It isn't available. Use props or a data function.
- Exporting shared constants from a client module. On the server they're references.
- Applying the theme in an effect and putting up with the flicker.
- Reading a cookie in the root layout when you don't need to. It makes everything depend on the request.
- Storing visitor data in a module variable. It gets mixed up between requests.
- Calling
cacheinside a component, or with object literals as arguments. - Inserting user data into an inline script. It's an open door to code injection.
Exercises
Exercise 1: following the system
With the "System" preference, if the user changes their operating system's mode while the page is open, AgendaViva doesn't react. Add that to ThemeProvider and explain why it isn't enough for subscribe to listen for that change.
Solution
// components/theme-provider.tsx (inside ThemeProvider; imports useEffect)
useEffect(() => {
const mediaQuery = matchMedia('(prefers-color-scheme: dark)')
const handleChange = () => applyTheme(readPreference())
mediaQuery.addEventListener('change', handleChange)
return () => mediaQuery.removeEventListener('change', handleChange)
}, [])useSyncExternalStore only re-renders if the value it reads changes. When the system changes, the preference is still 'system', so React would do nothing and the effect that applies the theme wouldn't run. Since what changes here isn't any state but the DOM, an effect with its cleanup is the right tool. The course keeps this addition.
Exercise 2: finding the leak
This module counts how many queries each request makes so it can be shown in the footer. What will it show in production? Propose a correct approach.
let queries = 0
export async function runQuery<T>(action: () => Promise<T>): Promise<T> {
queries += 1
return action()
}
export function totalQueries() {
return queries
}Solution
The count grows endlessly and mixes up every request since the server started. With several instances, on top of that, each visit would see a different number. React.cache gives you an object of each request's own:
import { cache } from 'react'
// The same object during a request; a different one in the next
const getCounter = cache(() => ({ queries: 0 }))
export async function runQuery<T>(action: () => Promise<T>): Promise<T> {
getCounter().queries += 1
return action()
}It's good for logging the total at the end, not for rendering it in the footer: that component may run before the queries do. To measure for real there are observability tools (10-05).
Exercise 3: context or not?
Decide how to share each value: (1) the currency, fixed for the whole application; (2) the current event between EventDetails and its server blocks; (3) whether the dashboard's sidebar is collapsed, read by the sidebar and by a button in the top bar; (4) the category filter; (5) the user's permissions, read by client buttons scattered across the dashboard.
Solution
- A module constant without a directive. It doesn't change.
- Props if they're direct children, or fetch it again with a function wrapped in
cache. - Client context in
ManagementLayout, which contains both. It's transient UI state. - The URL. It already is.
- Client context with server data, in
DashboardLayout: only the permissions, not the user. And it's for showing or hiding things; the real check is done on the server (08-04).
Conclusion
Context is a client tool that enters the application through a provider with children, placed as low as possible. Whatever must be visible before React starts, like the theme, is handled with an inline script and an attribute. On the server you share by requesting the data where it's needed, with React.cache to avoid repeating it, and never by storing anything about a visitor in a module. Libraries without the directive get wrapped.
You now know what crosses the boundary when you want it to. What's left is making sure that what you don't want doesn't cross it: a query, a key, an internal rule. In Server-Only Code and Environment Variables you'll set up those barriers and AgendaViva's configuration.
