Custom useContext Hook for Safety
What You'll Learn
You'll learn how to create a wrapper hook around useContext that throws an error when used outside its Provider, eliminating the need for repetitive undefined checks throughout your app.
The Problem with Raw useContext
When you use createContext<T>(undefined) with the undefined default pattern (as you learned in the previous lesson), every component that calls useContext must check if the value is undefined. This is tedious and error-prone—developers forget, and runtime errors slip through.
The Safety Wrapper Pattern
Create a custom hook that wraps useContext and validates the context value automatically:
import { createContext, useContext } from 'react';
interface AuthContextType {
user: string;
login: (name: string) => void;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
// The safety wrapper
function useAuth() {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error('useAuth must be used within AuthProvider');
}
return context;
}
Now in any component:
function Profile() {
// No need to check for undefined!
// TypeScript knows it's AuthContextType, not AuthContextType | undefined
const { user, login } = useAuth();
return <div>Welcome, {user}</div>;
}
Why This Works
The throw statement acts as a type guard. After that check, TypeScript knows context cannot be undefined, so the return type is the clean AuthContextType. You write the safety check once, in the hook, instead of in every consuming component.
Key Takeaway: A custom useContext wrapper that throws when the value is undefined centralizes safety checks, gives consumers a cleaner non-undefined type, and catches Provider mistakes immediately with clear error messages.