Course contentsShow
← TypeScript
Lesson 1526 of 1,79635. TypeScript with Framework Cross-ReferencesFree lesson

Typing Context Providers with createContext

Provide proper types to createContext including undefined handling for provider requirements.

Typing Context Providers with createContext

What you'll learn: How to provide proper type definitions to React's createContext that handle both the initial undefined state and provider requirements safely.


The Context Typing Challenge

React's createContext creates a context that can be consumed anywhere in your component tree. The tricky part: when you create a context, you must provide a default value, but often your context requires a provider to have meaningful data.

This creates a typing dilemma: do you lie and provide a fake default, or properly type the context as potentially undefined?

The Problem Without Proper Typing

When you call createContext, TypeScript needs to know what type of data flows through it. If you don't handle this carefully, you'll either:

  1. Force consumers to check for undefined everywhere (annoying)
  2. Lie with a fake default value (unsafe)
  3. Get type errors when creating the context (frustrating)

The Proper Pattern

The best approach acknowledges that context starts as undefined and requires a provider:

type ThemeContextType = {
  theme: 'light' | 'dark';
  toggleTheme: () => void;
};

// Create with undefined, acknowledging the truth
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);

Now consumers know the context might be undefined, which reflects reality before a provider exists.

The Custom Hook Safety Layer

Rather than forcing every consumer to handle undefined, create a custom hook that enforces the provider requirement:

function useTheme() {
  const context = useContext(ThemeContext);
  
  if (context === undefined) {
    throw new Error('useTheme must be used within a ThemeProvider');
  }
  
  return context;
}

This pattern gives you:

  • Type safety: Context starts as undefined (truth)
  • Runtime safety: Clear error if provider is missing
  • Consumer convenience: useTheme() returns ThemeContextType, not ThemeContextType | undefined

Consumers never handle undefined because the hook guarantees a provider exists or throws early.


Key Takeaway: Type createContext with T | undefined, pass undefined as the default, then create a custom hook that throws if the context is undefined—this pattern provides both compile-time honesty and runtime safety without burdening consumers with null checks.