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;
}

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.

Further reading

Problem with a question

State Management · Junior · question 23

Test yourself

Take the State Management · Junior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz