Skip to content

Context value undefined error

Quick summary

You called useContext but got undefined because the component is outside the provider tree or the context default is undefined.

Why this happens

  • The component using useContext is rendered outside the Context.Provider that supplies the value

  • The context was created with a default value of undefined and no provider wraps the consuming component

  • The provider value prop is undefined due to a conditional or loading state that has not resolved yet

Minimal example

✗ Broken code
const ThemeContext = createContext(undefined);
function Button() {
  const theme = useContext(ThemeContext);
  return <button className={theme.color}>Click</button>; // theme is undefined!
}
✓ Fixed code
const ThemeContext = createContext({ color: 'blue' });
function Button() {
  const theme = useContext(ThemeContext);
  return <button className={theme.color}>Click</button>; // safe default
}
// Or wrap with provider: <ThemeContext.Provider value={{color:'red'}}>

Providing a default value when creating the context ensures useContext always returns a usable object, even without a provider.

How to diagnose

  • Log the context value to confirm it is undefined: const ctx = useContext(MyContext); console.log(ctx)

  • Check the component tree to verify the provider wraps the component that calls useContext

  • Inspect the provider value prop to ensure it is not undefined or null at the time of consumption

How to fix

  • Wrap the consuming component with the Context.Provider and pass a valid value prop

  • Create the context with a meaningful default value instead of undefined so it works without a provider

  • Add a null check after useContext and throw a custom error with a helpful message if the value is undefined

How to prevent

  • Always provide a default value when creating context, or throw a descriptive error if the provider is missing

  • Use a custom hook that wraps useContext and throws if the value is undefined, enforcing provider usage

Related Resources

Related Glossary

Related Lessons

← Back to language