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

  1. app/providers.tsx with "use client": create the context and export a provider component.
  2. Render <Providers> in app/layout.tsx around children. The layout can stay a Server Component.
  3. Consume with useContext (or React 19's use(Context)) in Client Components.
  4. Server-rendered children passed 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.tsx
2"use client";
3
4import { createContext, use } from "react";
5
6type User = { id: string; name: string } | null;
7const UserContext = createContext<Promise<User> | null>(null);
8
9export function UserProvider({ userPromise, children }: { userPromise: Promise<User>; children: React.ReactNode }) {
10 return <UserContext value={userPromise}>{children}</UserContext>;
11}
12
13export 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 user
17}
18
19// 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.

Open in study app