This error occurs when a component tries to access properties from a React Context that has not been properly initialized or wrapped in its Provider. The context value is undefined, leading to property access errors when destructuring or reading from the context.
This error happens when you attempt to use React Context in a component, but the component is either not wrapped in the corresponding Context Provider, or the Provider's value is explicitly set to undefined or null. When you call useContext(MyContext), React looks up the component tree for the nearest Provider of that context. If no Provider is found, useContext returns the default value you provided when creating the context (or undefined if no default was provided). Attempting to destructure or access properties on undefined then triggers this error. React Context is designed to share data across a component tree without passing props manually through every level. However, for Context to work properly, the consuming components must be descendants of a Provider component that supplies the context value. If this relationship is broken, the context value will be undefined, causing runtime errors when your code assumes the value exists. This is particularly common when refactoring components, moving them to different parts of the component tree, or when the Provider is conditionally rendered and sometimes not present in the tree.
Ensure your Context Provider wraps all components that need access to the context. The Provider must be an ancestor in the component tree.
// ❌ WRONG - Consumer is not wrapped by Provider
function App() {
return (
<div>
<UserProfile /> {/* This will get undefined */}
<UserProvider>
<Dashboard />
</UserProvider>
</div>
);
}
// ✅ CORRECT - All consumers wrapped by Provider
function App() {
return (
<UserProvider>
<div>
<UserProfile /> {/* This will work */}
<Dashboard />
</div>
</UserProvider>
);
}Move the Provider higher in your component tree to wrap all components that need the context.
Verify that the value prop passed to your Provider is properly initialized and not undefined or null.
// ❌ WRONG - Value is undefined
function UserProvider({ children }) {
const [user, setUser] = useState(); // undefined initially
return (
<UserContext.Provider value={user}>
{children}
</UserContext.Provider>
);
}
// ✅ CORRECT - Provide object even when loading
function UserProvider({ children }) {
const [user, setUser] = useState(null);
const value = {
user,
setUser,
isLoading: user === null
};
return (
<UserContext.Provider value={value}>
{children}
</UserContext.Provider>
);
}Always provide a valid object as the context value, even during loading states.
Provide a sensible default value when creating your context to prevent undefined errors.
// ❌ WRONG - No default value
const UserContext = createContext();
// ✅ BETTER - Provide default value
const UserContext = createContext({
user: null,
setUser: () => {},
isLoading: true
});
// ✅ BEST - Use TypeScript and define interface
interface UserContextType {
user: User | null;
setUser: (user: User | null) => void;
isLoading: boolean;
}
const UserContext = createContext<UserContextType>({
user: null,
setUser: () => {},
isLoading: true
});A default value serves as a fallback and makes the expected shape of your context explicit.
Build a custom hook that validates the context is being used within a Provider and provides helpful error messages.
// Create context
const UserContext = createContext(undefined);
// Custom hook with validation
function useUser() {
const context = useContext(UserContext);
if (context === undefined) {
throw new Error(
'useUser must be used within a UserProvider. ' +
'Wrap your component tree with <UserProvider>.'
);
}
return context;
}
// Provider component
function UserProvider({ children }) {
const [user, setUser] = useState(null);
const value = { user, setUser };
return (
<UserContext.Provider value={value}>
{children}
</UserContext.Provider>
);
}
// Usage in components
function UserProfile() {
const { user } = useUser(); // Will throw clear error if not in Provider
return <div>{user?.name}</div>;
}This pattern provides immediate, clear feedback when context is used incorrectly.
Ensure you're importing and using the correct Context object, not creating a duplicate.
// userContext.js
export const UserContext = createContext(null);
// ❌ WRONG - Creating new context instead of importing
import { createContext, useContext } from 'react';
const UserContext = createContext(null); // Different instance!
function MyComponent() {
const user = useContext(UserContext); // Won't find Provider
}
// ✅ CORRECT - Import the same context
import { useContext } from 'react';
import { UserContext } from './userContext';
function MyComponent() {
const user = useContext(UserContext); // Works correctly
}Always import the context from a single source of truth.
TypeScript Best Practices: When using TypeScript with Context, avoid using undefined as the default value. Instead, either provide a complete default value or use a pattern where undefined signals "not wrapped in Provider" and your custom hook throws an error. This prevents silent failures and catches misuse at development time.
Multiple Contexts: When using multiple contexts, ensure each has its own Provider and that Providers are nested in the correct order. Context Providers can be composed, but the order matters if contexts depend on each other.
Performance Considerations: Context value changes trigger re-renders in all consuming components. To optimize, use useMemo to memoize the context value object, or split related but independent state into separate contexts. Only components that consume a specific context will re-render when that context changes.
Testing: When testing components that use context, always wrap them in the appropriate Provider(s) in your test setup. Testing libraries like React Testing Library make this straightforward with wrapper functions.
Server Components (Next.js App Router): Context only works in Client Components. If you're using Next.js 13+ with the App Router, ensure your context providers and consuming components have 'use client' directive at the top of the file. Server Components cannot use Context.
Development vs Production: React's development mode provides helpful warnings when context is used incorrectly, but these may not appear in production builds. Always test your context setup thoroughly in development.
Prop spreading could cause security issues
Prop spreading could cause security issues
Error: error:0308010C:digital envelope routines::unsupported
Error: error:0308010C:digital envelope routines::unsupported
React Hook "useEffect" is called conditionally. React Hooks must be called in the exact same order in every component render.
React Hook useEffect placed inside a condition
Hook can only be called inside the body of a function component
Hook can only be called inside the body of a function component
Rollup failed to resolve import during build
How to fix "Rollup failed to resolve import" in React