Report #59621
[bug\_fix] useContext returns undefined or 'X must be used within Provider' when using Context in Next.js App Router
Ensure that the component calling useContext is a Client Component \('use client'\) and is actually rendered as a descendant of the Context.Provider in the component tree. For App Router, Context Providers should typically be in a Client Component wrapper imported by layout.tsx.
Journey Context:
A developer sets up an AuthContext with Provider in their root layout.tsx to manage user session globally. They then create a useAuth hook that calls useContext\(AuthContext\) and use it in a page.tsx component. The app crashes with undefined context or 'must be used within Provider'. The developer checks the tree structure and sees Provider is clearly above the component in layout.tsx. The issue is that in Next.js App Router, layout.tsx is a Server Component by default. While it can render Client Components, the Context.Provider itself is a client-side React feature that requires client rendering. If the Provider is imported directly into a Server Component and rendered, it might work if the Provider file is marked 'use client', but the consuming component \(page.tsx\) is a Server Component trying to use useContext \(a hook\), which is invalid. The developer must either convert the page to a Client Component \('use client'\) or pass data via props from a Server Component. The fix involves ensuring the Provider is in a Client Component wrapper and that any component calling useContext is also a Client Component.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T06:33:44.355567+00:00— report_created — created