How to fix Context default value is undefined but Consumer expects a value in React

ReactINTERMEDIATEMEDIUMUpdated Dec 9, 2025ยท 91 views

This error occurs when React Context is created without a default value (or with undefined) and components try to consume it outside of a Provider. The Consumer receives undefined and fails when trying to access properties or destructure the context value.

Quick fix

Fixes Context default value is undefined but Consumer expects a value

import { createContext, useContext } from 'react';

interface UserContextType {
  username: string;
  role: string;
}

const UserContext = createContext<UserContextType | undefined>(undefined);

// Custom hook with error checking
export function useUser() {
  const context = useContext(UserContext);
  if (context === undefined) {
    throw new Error('useUser must be used within a UserProvider');
  }
  return context;
}

export { UserContext };
  1. Add runtime check with custom hook
  2. Ensure Provider wraps all consumers
  3. Use type union with null for TypeScript
  4. Provide meaningful default values for simple contexts
react โ€” error
import { createContext, useContext } from 'react';
interface UserContextType {
username: string;
role: string;
}
const UserContext = createContext<UserContextType | undefined>(undefined);
// Custom hook with error checking
export function useUser() {
const context = useContext(UserContext);
if (context === undefined) {
throw new Error('useUser must be used within a UserProvider');
}
return context;
}
export { UserContext };
Context default value is undefined but Consumer expects a value

What this error means

This error occurs when you create a React Context using `createContext()` without providing a default value (or explicitly passing `undefined`), and then try to consume that context in a component that isn't wrapped by the corresponding Provider. When Context is consumed outside of a Provider, React falls back to the default value passed to `createContext()`. If that default value is `undefined`, any attempt to destructure it or access its properties will fail. This commonly happens with TypeScript when creating typed contexts, as developers often initialize the context with `undefined` to satisfy type requirements. The error typically manifests as "Cannot read property 'x' of undefined" or "Cannot destructure property 'x' of undefined" when using `useContext` or Context.Consumer in components that aren't properly wrapped by the Provider component.

Typical symptoms

  • TypeError: Cannot read property of undefined when accessing context values
  • Cannot destructure property from undefined when using object destructuring with useContext
  • Components render with no context data when placed outside Provider tree
  • TypeScript errors about possibly undefined context values
  • Context hook returns undefined instead of expected object
  • Runtime errors only in certain routes or component trees where Provider is missing

Common causes

  1. Creating Context with createContext() without a default value or with undefined explicitly
  2. Using useContext or Context.Consumer in components not wrapped by the Provider
  3. Provider component placed too low in the component tree, missing some consumers
  4. Conditional rendering of Provider that sometimes excludes it from the tree
  5. TypeScript setup where context type doesn't include undefined, masking the issue
  6. Testing components in isolation without wrapping them in the required Provider

How to fix "Context default value is undefined but Consumer expects a value"

1Add runtime check with custom hook

Create a custom hook that throws a helpful error if context is undefined:

typescript
import { createContext, useContext } from 'react';

interface UserContextType {
  username: string;
  role: string;
}

const UserContext = createContext<UserContextType | undefined>(undefined);

// Custom hook with error checking
export function useUser() {
  const context = useContext(UserContext);
  if (context === undefined) {
    throw new Error('useUser must be used within a UserProvider');
  }
  return context;
}

export { UserContext };

This provides a clear error message pointing to the actual problem instead of cryptic undefined errors.

2Ensure Provider wraps all consumers

Verify that all components using the context are wrapped by the Provider:

tsx
import { UserContext } from './UserContext';

function App() {
  const userData = { username: 'alice', role: 'admin' };

  return (
    <UserContext.Provider value={userData}>
      {/* All components here can safely use useUser() */}
      <Dashboard />
      <Settings />
    </UserContext.Provider>
  );
}

Check your component tree to ensure the Provider is placed high enough to cover all consumers. Use React DevTools to inspect the component hierarchy.

3Use type union with null for TypeScript

For TypeScript projects, use a union type that includes null or undefined:

typescript
const UserContext = createContext<UserContextType | null>(null);

export function useUser() {
  const context = useContext(UserContext);
  if (!context) {
    throw new Error('useUser must be used within a UserProvider');
  }
  return context;
}

This approach makes it explicit in the type system that the context can be null, forcing you to handle the case properly.

4Provide meaningful default values for simple contexts

For simple contexts (primitives, enums), provide a sensible default:

typescript
type Theme = 'light' | 'dark';
const ThemeContext = createContext<Theme>('light');

// No custom hook needed - consumers always get a valid value
export function useTheme() {
  return useContext(ThemeContext);
}

This works well for contexts that have reasonable defaults, but isn't suitable for complex state that must come from a Provider.

5Use non-null assertion for advanced cases

If you're certain the Provider will always be present, use TypeScript's non-null assertion:

typescript
const UserContext = createContext<UserContextType>(undefined!);

Warning: This bypasses TypeScript's safety checks. Only use this if you're absolutely sure all consumers will be wrapped by a Provider. The custom hook approach (step 1) is safer and provides better error messages.

6Wrap test components with Provider

When testing components that use context, always provide a test Provider:

typescript
import { render } from '@testing-library/react';
import { UserContext } from './UserContext';

function renderWithContext(ui: React.ReactElement, userData = mockUserData) {
  return render(
    <UserContext.Provider value={userData}>
      {ui}
    </UserContext.Provider>
  );
}

test('displays user name', () => {
  renderWithContext(<UserProfile />);
  // assertions...
});

This ensures your tests don't encounter undefined context values.

Advanced notes

Generic Context Factory Pattern: For applications with multiple contexts, create a reusable factory function:

typescript
function createGenericContext<T>() {
  const Context = createContext<T | undefined>(undefined);

  function useGenericContext() {
    const context = useContext(Context);
    if (context === undefined) {
      throw new Error('Context must be used within its Provider');
    }
    return context;
  }

  return [useGenericContext, Context.Provider] as const;
}

// Usage:
const [useAuth, AuthProvider] = createGenericContext<AuthContextType>();

Default Values vs Provider Pattern: React's documentation notes that the defaultValue argument is primarily useful for testing components in isolation. For production code, the Provider pattern with runtime checks is more robust and provides better error messages.

Optional Chaining Approach: An alternative to custom hooks is using optional chaining everywhere:

typescript
const user = useContext(UserContext);
return <div>{user?.username}</div>;

However, this silently fails and makes it harder to catch Provider placement bugs. The custom hook approach (with explicit error throwing) is generally preferred.

Context Splitting: If you find yourself constantly checking for undefined context, consider whether your context is too large. Split it into multiple smaller contexts, each with clear Provider boundaries and specific purposes.

Frequently asked questions

What does "Context default value is undefined but Consumer expects a value" mean?
This error occurs when you create a React Context using createContext() without providing a default value (or explicitly passing undefined), and then try to consume that context in a component that isn't wrapped by the corresponding Provider. When Context is consumed outside of a Provider, React falls back to the default value passed to createContext(). If that default value is undefined, any attempt to destructure it or access its properties will fail.
How do I fix "Context default value is undefined but Consumer expects a value"?
This error occurs when React Context is created without a default value (or with undefined) and components try to consume it outside of a Provider. The Consumer receives undefined and fails when trying to access properties or destructure the context value.
What causes "Context default value is undefined but Consumer expects a value"?
Creating Context with createContext() without a default value or with undefined explicitly Using useContext or Context.Consumer in components not wrapped by the Provider Provider component placed too low in the component tree, missing some consumers
Is the "Context default value is undefined but Consumer expects a value" error serious?
It is a medium-severity error โ€” more of a blocker than a risk. The steps above resolve it.

Official resources & further reading