Sub topic 13
Typing context and its provider
This chapter assumes you know basic React (function components, props, state, JSX) and TypeScript fundamentals (interfaces, unions, generics). It also assumes your project is already set up for strict TSX checking.
The problem with context defaults
createContext needs a default value. That value is used when a component reads the context outside any provider. In most apps there is no sensible default, because the real value comes from state inside the provider.
If you pass a fake default such as {}, TypeScript complains, or you cast it with as ThemeContextValue. The cast hides the bug. A component rendered outside the provider then gets a broken object and fails later, far from the cause.
A better approach is to make the missing provider part of the type.
Step 1: Describe the value and create the context
Define the shape of the value first. Then give createContext a union of that shape and null.
import { createContext, useContext, useState, type ReactNode } from "react";
type Theme = "light" | "dark";
interface ThemeContextValue {
theme: Theme;
setTheme: (theme: Theme) => void;
}
const ThemeContext = createContext<ThemeContextValue | null>(null);The type argument ThemeContextValue | null tells TypeScript that the context can be null. The default null is honest: before a provider exists, there is no value.
Step 2: Type the provider
The provider is a normal component. Its only prop is children, typed as ReactNode. Inside, it owns the state and passes it down.
export function ThemeProvider({ children }: { children: ReactNode }) {
const [theme, setTheme] = useState<Theme>("light");
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
}The value prop is checked against ThemeContextValue | null. If you forget setTheme, or pass a wrong theme string, the compiler reports an error here.
Step 3: Narrow with a custom hook
Consumers should not call useContext(ThemeContext) directly. They would have to check for null every time. Wrap the call in a hook that checks once and throws.
export function useTheme(): ThemeContextValue {
const ctx = useContext(ThemeContext);
if (ctx === null) {
throw new Error("useTheme must be used inside ThemeProvider");
}
return ctx;
}After the if, TypeScript narrows ctx from ThemeContextValue | null to ThemeContextValue. The return type annotation makes that promise explicit. Components now get a non-null value, or a clear error message that names the fix.
Using the hook
function ThemeToggle() {
const { theme, setTheme } = useTheme();
return (
<button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>
Current: {theme}
</button>
);
}No null check is needed, and setTheme only accepts "light" or "dark".
Common errors
| Mistake | Result | Fix | Column |
|---|---|---|---|
| `createContext({} as ThemeContextValue)` | Missing provider goes unnoticed | Use `ThemeContextValue \ | null` and a checking hook |
| Exporting the raw context and calling `useContext` everywhere | A `null` check in every component | Export only the provider and the hook | |
| Omitting the return type on the hook | Narrowing may be less obvious to readers | Annotate it, as in `useTheme(): ThemeContextValue` |
Exercise
Why does the context use ThemeContextValue | null as its type instead of a cast default like {} as ThemeContextValue, and where does the null get removed from the type?
Show answer
The cast hides the case where a component renders outside the provider, so the bug shows up later as a confusing failure. Using | null makes that case visible to the compiler. The useTheme hook removes null by checking ctx === null and throwing, so TypeScript narrows the returned value to ThemeContextValue.
Exercise
Write a useUser hook for a UserContext created with createContext<User | null>(null). It must return User and throw an error if used outside the provider.
Show answer
function useUser(): User { const user = useContext(UserContext); if (user === null) { throw new Error("useUser must be used inside UserProvider"); } return user; }