Report #4648
[bug\_fix] Cannot read properties of undefined \(reading 'X'\) when consuming React Context
Provide a default value in createContext\(defaultValue\) that matches the expected context shape \(e.g., an empty object with safe default methods, or null with checks\), or wrap the consumer in the corresponding Provider. Better yet, create a custom useContext hook that checks for undefined and throws a descriptive error if the context is used outside its Provider. Root cause: When useContext is called outside its Provider tree, it returns the default value passed to createContext. If no default was provided \(undefined\), accessing properties on it causes a runtime TypeError.
Journey Context:
Developer creates an AuthContext using const AuthContext = createContext\(\). They build a useAuth\(\) helper that calls useContext\(AuthContext\) and destructures \{ user, login \}. The main App component wraps routes in . However, a developer on the team creates a new utility component inside a different file and calls useAuth\(\) at the top level of that file \(outside any component\) or uses it in a component that is accidentally rendered outside the Provider tree \(e.g., in a parallel route or layout oversight\). The app crashes with Cannot read properties of undefined \(reading 'user'\). Developer checks the context file, realizes createContext\(\) was called with no arguments, defaulting to undefined. They fix it by passing a safe default like \{ user: null, login: \(\) => \{\} \} to createContext, or by adding a runtime check in useAuth: const ctx = useContext\(AuthContext\); if \(\!ctx\) throw new Error\('useAuth must be used within AuthProvider'\). This provides a clear stack trace pointing to the misplaced component.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-15T19:50:40.352029+00:00— report_created — created