Course contentsShow
← React
Lesson 2373 of 2,39651. TypeScript with React BasicsFree lesson

The undefined Default Value Pattern

Why createContext<MyType | undefined>(undefined) is the standard pattern and what problem it solves.

The undefined Default Value Pattern

What you'll learn: Why createContext<MyType | undefined>(undefined) is the go-to pattern for type-safe context and what problem it solves.

The Problem with Default Values

When you create a typed context, TypeScript forces you to provide a default value. But often, you don't have a sensible default—the real value only exists inside a Provider. If you make up a fake default just to satisfy TypeScript, you risk:

  • Components accidentally using that fake value
  • Forgetting to wrap components in a Provider
  • Runtime bugs that TypeScript doesn't catch

The Solution: Explicitly Allow undefined

The pattern looks like this:

type AuthContextType = {
  user: User;
  login: () => void;
};

const AuthContext = createContext<AuthContextType | undefined>(undefined);

By typing the context as MyType | undefined and passing undefined as the default, you're being honest: "This context has no value until you wrap something in a Provider."

Forcing Safe Usage

Now when you consume the context, TypeScript requires you to handle the undefined case:

const auth = useContext(AuthContext);
// auth is AuthContextType | undefined

if (!auth) {
  throw new Error('useAuth must be used within AuthProvider');
}
// Now auth is AuthContextType

This forces you to fail fast with a clear error message if someone forgets the Provider, rather than silently using a fake default value.

Key Takeaway: The createContext<T | undefined>(undefined) pattern trades a bit of boilerplate (the undefined check) for massive safety—it makes Provider-less usage impossible to miss and prevents silent bugs from fake defaults.