Report #9652
[bug\_fix] Cannot destructure property 'X' of 'useContext\(...\)' as it is undefined / useContext returns undefined / Context value is undefined in consumer
Ensure the Provider component wraps the Consumer component in the React tree. In Next.js App Router, ensure the Provider component has the \`'use client'\` directive and is imported into a layout that wraps the pages where the context is consumed. Verify there are no duplicate React instances \(check \`npm ls react\`\) that would create separate context objects. If context is optional, provide a default value to \`createContext\(defaultValue\)\` to avoid undefined errors.
Journey Context:
Developer creates an \`AuthContext\` using \`createContext\` and exports \`useAuth\` hook that calls \`useContext\(AuthContext\)\`. Creates an \`AuthProvider\` component that wraps children with \`\`. In Next.js App Router, developer imports \`AuthProvider\` into \`app/layout.tsx\` \(the root layout\) and wraps \`\{children\}\`. Then in \`app/dashboard/page.tsx\`, calls \`const \{ user \} = useAuth\(\)\`. Immediately crashes with "Cannot destructure property 'user' of 'useAuth\(...\)' as it is undefined". Developer checks imports - \`useAuth\` is imported from the correct file. Checks that \`AuthProvider\` is indeed in layout.tsx. Realizes that \`app/layout.tsx\` is a Server Component by default. While it can import \`AuthProvider\`, if \`AuthProvider\` is not marked with 'use client', or if the context is consumed in a Server Component \(page.tsx is a Server Component by default\), the context won't work because hooks can't run on the server. Developer moves the dashboard page to a Client Component by adding 'use client', or wraps the specific part using context in a Client Component. Alternatively, realizes the Provider itself must be a Client Component \('use client'\) so it can hold state, and it must be placed in a layout that properly wraps the route. After ensuring the Provider is a Client Component and the Consumer is also a Client Component \(or using the context in a way that respects server/client boundaries\), the undefined error resolves.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T08:44:19.274243+00:00— report_created — created