0Pricing
React Academy · Lesson

Typing Context & Custom Hooks

Create typed context with default values and write custom hooks with explicit return types.

Typed Context with createContext

Pass the context type and a default value to createContext. Use null as default when the context must be used inside a provider, and handle it with a guard.

interface AuthContextType {
  user: User | null;
  login: (credentials: Credentials) => Promise<void>;
  logout: () => void;
}

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

The Guard Hook Pattern

Create a custom hook that reads the context and throws if it's used outside its provider. This eliminates null checks at every call site.

export function useAuth(): AuthContextType {
  const ctx = useContext(AuthContext);
  if (!ctx) throw new Error('useAuth must be used within AuthProvider');
  return ctx;
}

All lessons in this course

  1. Typing Props & Component Return Types
  2. Typing Events & Refs in TypeScript
  3. Generic Components & Utility Types
  4. Typing Context & Custom Hooks
← Back to React Academy