Next.jsMedium
How do you use context in the App Router?
React context only works in Client Components. Create the context and its provider in a "use client" file, render the provider in a layout (a Server Component), and pass server-fetched data into it as props. Server Components cannot read context; they pass data via props or call cached functions directly.
Steps
app/providers.tsxwith"use client": create the context and export a provider component.- Render
<Providers>inapp/layout.tsxaroundchildren. The layout can stay a Server Component. - Consume with
useContext(or React 19'suse(Context)) in Client Components. - Server-rendered
childrenpassed through the provider stay Server Components.
Tips
- Render providers as deep as possible. Wrapping only the part that needs it helps Next.js optimize the static parts.
- Seed from the server: fetch the user or settings in the layout and pass them to the provider.
- Pass a promise to the provider and read it with
use()in consumers, so the layout does not block on the data. - With React 19 you can render
<ThemeContext value={...}>directly instead of<ThemeContext.Provider>.
For Server Components
- Need the same data in many Server Components? Call a
React.cache-wrapped function in each one; it runs once per request. - Root-level params like a locale segment can be read anywhere with
next/root-params(16.3) instead of prop drilling.
Pitfall
Context changes re-render every consumer. For frequently changing global state, consider Zustand, Jotai or splitting contexts.
Code example
tsx
1// app/providers.tsx2"use client";34import { createContext, use } from "react";56type User = { id: string; name: string } | null;7const UserContext = createContext<Promise<User> | null>(null);89export function UserProvider({ userPromise, children }: { userPromise: Promise<User>; children: React.ReactNode }) {10 return <UserContext value={userPromise}>{children}</UserContext>;11}1213export function useUser() {14 const promise = use(UserContext);15 if (!promise) throw new Error("useUser must be used inside UserProvider");16 return use(promise); // suspends until the server resolves the user17}1819// app/layout.tsx (Server Component)20// import { getCurrentUser } from "@/lib/auth";21// export default function RootLayout({ children }) {22// return (23// <html lang="en"><body>24// <UserProvider userPromise={getCurrentUser()}>{children}</UserProvider>25// </body></html>26// );27// }
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.