Skip to content

FlashcardNot attempted

The typed context recipe

Recall it before you reveal

How do you type a React context so consumers never deal with undefined?

Space to reveal
Show answer & explanation

1. Type the value and default to undefined: createContext<Ctx | undefined>(undefined). 2. Export a hook that narrows by throwing:

export function useAuth() {
const ctx = useContext(AuthContext);
if (!ctx) throw new Error('useAuth must be used inside <AuthProvider>');
return ctx; // Ctx
}

3. Type setters from useState as Dispatch<SetStateAction<T>>.

Avoid createContext({} as Ctx): it compiles but turns a missing provider into a runtime crash. If the context has a sensible default (a theme object), pass it and let inference type the context.