State Management · Junior · Question 23 of 75
Why wrap useContext in a custom hook like useAuth()?
export function useAuth() {
const ctx = useContext(AuthContext);
if (!ctx) throw new Error("useAuth must be used within AuthProvider");
return ctx;
}- ✓Correct answer: To hide the context object and fail clearly when the provider is missing
- 2Because
useContextcan't be called directly in components - 3To make the context value immutable
Explanation
Consumers import one hook instead of the context object, TypeScript gets a non-null type, and a missing provider produces a readable error instead of undefined somewhere deep in the code.