Lingua-e
JavaScript

What is a Context Without Provider?

← Errors

useContext() returns the default value passed to createContext() when there is no matching Provider in the component tree above it. If the default value is null or undefined and you access properties on it, you get a TypeError at runtime.

Why it happens

  • The component using useContext is rendered outside the Provider tree.
  • The Provider is placed too low in the component tree, missing some consumers.
  • createContext() was called with null as the default and no Provider wraps the consumer.
  • The Provider and the consumer are in different React roots.

Examples

JavaScript

Code that triggers the error

const ThemeContext = createContext(null);

function Button() {
  const theme = useContext(ThemeContext); // no Provider above
  return <button style={{ color: theme.primary }}>Click</button>;
}

Error output

TypeError: Cannot read properties of null (reading 'primary')

How to fix it

Ensure the Provider wraps all components that consume the context. Provide a meaningful default value to createContext() so the app degrades gracefully without a Provider. Create a custom hook that throws a clear error message if the context value is null.

Fixed code

function App() {
  return (
    <ThemeContext.Provider value={{ primary: "blue" }}>
      <Button />
    </ThemeContext.Provider>
  );
}

Related errors

Ready to practice your English at work?

Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.

Try Lingua-e for free