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
- Typing Props & Component Return Types
- Typing Events & Refs in TypeScript
- Generic Components & Utility Types
- Typing Context & Custom Hooks