Typing useContext with Type Safety
You'll learn how to consume context with full type safety and handle the case where context might be missing.
The Context Consumer Challenge
When you call useContext(), TypeScript needs to know what type the context value has. If your context's default value is undefined, you'll need to handle that possibility—or design your hook to guarantee the context exists.
Type-Safe Context Consumption
The safest pattern is to create a custom hook that throws an error if the context is used outside a provider:
const ThemeContext = createContext<{ theme: string } | undefined>(undefined);
function useTheme() {
const context = useContext(ThemeContext);
if (context === undefined) {
throw new Error('useTheme must be used within ThemeProvider');
}
return context; // Now TypeScript knows it's NOT undefined
}
// In your components:
function Button() {
const { theme } = useTheme(); // No need to check for undefined!
return <button className={theme}>Click me</button>;
}
This pattern accomplishes two things: it narrows the type from { theme: string } | undefined to just { theme: string }, and it prevents runtime bugs by catching misuse early.
Think of It Like a Safety Guard
Imagine a building where certain rooms require a key card. Your custom hook is like a guard at the door—it checks for the card (the provider) and either lets you through with confidence or stops you immediately with a clear error message. Without this guard, you'd be checking for the card at every door inside.
The alternative—handling undefined at every call site—is tedious and error-prone:
const context = useContext(ThemeContext);
if (!context) return null; // Repeated everywhere!
Key Takeaway: Create a custom hook that throws when context is undefined, so consumers get guaranteed non-null values and clear error messages when providers are missing.