4.5 App Router State Management
In the App Router, passing state between Server Components and Client Components requires a clear understanding of component boundaries. This module covers how to integrate the Context API correctly within Next.js 15, ensuring you can manage global state efficiently without sacrificing server-side rendering benefits.
The Context Provider Pattern
Server Components cannot use React Context. If you attempt to create or consume a context inside a Server Component, Next.js will throw an error. However, your application will almost certainly need global state for themes, user sessions, or UI toggles.
The solution is the Client Provider Pattern. You create a Client Component that purely acts as a Context Provider, and then you wrap your Server Components (like the children in your root layout) with this provider.
// app/providers/ThemeProvider.tsx 'use client'; import { createContext, useContext, useState } from 'react'; const ThemeContext = createContext(null); export default function ThemeProvider({ children }: { children: React.ReactNode }) { const [theme, setTheme] = useState('dark'); return ( <ThemeContext.Provider value={{ theme, setTheme }}> {children} </ThemeContext.Provider> ); }
Notice that we use 'use client' at the top. This marks the provider as a Client Component. But here is the critical part: children passed to a Client Component can still be Server Components!
Applying the Provider in the Root Layout
To make the context available throughout your app, you render the Client Provider inside your Root Layout.
// app/layout.tsx import ThemeProvider from './providers/ThemeProvider'; export default function RootLayout({ children }: { children: React.ReactNode }) { return ( <html lang='en'> <body> <ThemeProvider> {children} </ThemeProvider> </body> </html> ); }
Because Next.js renders the children as Server Components first and passes the resulting React nodes to the ThemeProvider, you don't lose Server Component benefits for your pages.
Consuming Context
Only Client Components can consume the context using useContext. If a component needs to read the theme or toggle it, it must be marked with 'use client'.
// app/components/ThemeToggle.tsx 'use client'; import { useContext } from 'react'; import { ThemeContext } from '../providers/ThemeProvider'; export default function ThemeToggle() { const { theme, setTheme } = useContext(ThemeContext); return ( <button onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}> Toggle Theme </button> ); }
When NOT to use Context
Don't use Context for server data. If you fetch data from a database, pass it down via props, or fetch it directly in the Server Components that need it. Next.js automatically dedupes fetch requests, so it's perfectly safe and efficient to fetch the same data in multiple Server Components.
Knowledge Check
Ready to test your understanding of 4.5 App Router State Management?