When Context API is the right choice
Context API is useful when several components need the same low-frequency state. It is not a replacement for every data-fetching or server cache problem, but it works well for shared UI state that changes occasionally.
- Theme mode and layout preferences
- Authenticated user display state
- Sidebar, modal or navigation state
- Small form wizard state shared across steps
Provider placement in the App Router
In Next.js, Context providers must be client components, but they do not have to wrap more of the tree than necessary. Place providers close to the components that need them so server-rendered content stays fast and crawlable.
- Create a client provider component
- Wrap only the route group or layout that needs shared state
- Expose a custom hook for safer context usage
- Keep SEO page copy outside unnecessary client boundaries
Avoiding performance problems
Context updates re-render consumers, so split unrelated state into separate providers and memoize values when it matters. For frequently changing server data, prefer server fetching or a dedicated data cache.
- Do not put large mutable objects in a global provider
- Separate auth, theme and utility contexts
- Keep provider values stable when possible
- Use route metadata for SEO instead of client-only document updates