Skip to content

QuizNot attempted

Typed context with a guard hook

What is the return type of useUser(), and what happens if a component calls it outside <UserProvider>?
type UserCtx = { user: User | null; setUser: Dispatch<SetStateAction<User | null>> };
const UserContext = createContext<UserCtx | undefined>(undefined);
export function useUser() {
const ctx = useContext(UserContext);
if (!ctx) throw new Error('useUser must be used inside <UserProvider>');
return ctx;
}
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • UserCtx; it throws a clear error at render time
  • useContext returns UserCtx | undefined, and the throw narrows it, so the hook's inferred return type is plain UserCtx and consumers never write value?.user
  • a missing provider becomes a loud error instead of a silent undefined.
  • Not UserCtx | undefined: the if (!ctx) throw removes undefined by control-flow narrowing.
  • Not 'returns an empty object': that is the createContext({} as UserCtx) hack, which lies to the compiler and crashes later on setUser.
  • Not any: createContext<T> keeps T.