Sub topic 13
Typing context and its provider
React context lets a provider component share a value with any descendant, without passing props through each level. TypeScript needs two pieces of information to check this. It needs the shape of the value, and it needs to know what a consumer sees when no provider exists above it. This chapter covers both and shows a pattern that keeps consumers free of null checks.
Prerequisites
This chapter assumes you know the following:
- Basic React: function components, props,
useState, and JSX. - TypeScript fundamentals: interfaces, type aliases, unions, and generics.
- The earlier chapters on typing props,
children,useState, and custom hooks.
The problem: a default value you do not have
createContext requires a default value. React uses it only when a component calls useContext without a matching provider above it.
TypeScript infers the context type from that default. That causes trouble when the real value comes from state inside the provider.
import { createContext } from "react";
// Inferred as Context<{ theme: string }>. The shape is too loose,
// and there is no setter at all.
const BadContext = createContext({ theme: "light" });You could build a fake default that satisfies the full type, such as a no-op setTheme. That hides bugs, because a consumer outside the provider would silently use the fake.
The common approach is to widen the type to include null, then narrow it in one place.
Step 1: describe the value
Define the value type first. A named type documents the contract and is reused by the provider and the hook.
type Theme = "light" | "dark";
interface ThemeContextValue {
theme: Theme;
setTheme: (theme: Theme) => void;
}Use a literal union for Theme, not string. Then setTheme("blue") is a compile error.
Step 2: create the context with a null default
Pass the type argument explicitly. Without it, TypeScript infers the type of null alone, and the provider could not accept a real value.
import { createContext } from "react";
const ThemeContext = createContext<ThemeContextValue | null>(null);The type is now Context<ThemeContextValue | null>. A raw useContext(ThemeContext) returns ThemeContextValue | null, so TypeScript forces a null check wherever you use it.
Step 3: type the provider
The provider is an ordinary function component. It takes children: ReactNode, owns the state, and passes the value down.
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);
export function ThemeProvider({ children }: { children: ReactNode }) {
const [theme, setTheme] = useState<Theme>("light");
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
}
export function useTheme(): ThemeContextValue {
const ctx = useContext(ThemeContext);
if (ctx === null) {
throw new Error("useTheme must be used inside ThemeProvider");
}
return ctx;
}Three details matter here:
useState<Theme>("light")needs the explicit argument. Without it, TypeScript infersstringfrom the initial value, andsetThemewould not match(theme: Theme) => void.- The
valueprop is checked againstThemeContextValue | null. If you forgetsetTheme, the compiler reports it. ReactNodeaccepts strings, numbers, elements, fragments, arrays,null, andundefined.
Step 4: narrow in a custom hook
The useTheme hook is the key part of the pattern. It does the null check once, so every consumer receives a plain ThemeContextValue.
function Toolbar() {
const { theme, setTheme } = useTheme();
return (
<button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>
Current: {theme}
</button>
);
}Toolbar has no null check and no non-null assertion (!). If someone renders it outside ThemeProvider, the thrown error names the exact mistake at the first render. That is better than a vague Cannot read properties of null further away.
Export the hook and the provider. Do not export ThemeContext itself. If the raw context stays private, nobody can bypass the checked hook.
Choosing a default strategy
There are three common ways to handle the missing-provider case. The right one depends on whether a sensible default exists.
| Strategy | Context type | Consumer sees | Use when | Column |
|---|---|---|---|---|
| `null` default plus throwing hook | `T \ | null` | `T` | The value needs provider state. This is the usual case. |
| Real default value | `T` | `T` | A genuine fallback exists, such as a default locale. | |
| `undefined` default plus throwing hook | `T \ | undefined` | `T` | Same as `null`. Pick one and stay consistent. |
If you pick a real default, the provider is optional. Components outside it simply get the fallback, which is fine for read-only configuration.
A reusable helper
If your app has many contexts, the null-check pattern repeats. A small generic helper removes the duplication.
import { createContext, useContext } from "react";
export function createRequiredContext<T>(name: string) {
const Context = createContext<T | null>(null);
Context.displayName = name;
function useRequiredContext(): T {
const ctx = useContext(Context);
if (ctx === null) {
throw new Error(`use${name} must be used inside ${name}Provider`);
}
return ctx;
}
return [Context.Provider, useRequiredContext] as const;
}The as const keeps the return a tuple, as in the custom hooks chapter. Usage looks like this:
import { useState, type ReactNode } from "react";
import { createRequiredContext } from "./createRequiredContext";
interface CounterValue {
count: number;
increment: () => void;
}
const [CounterContextProvider, useCounter] =
createRequiredContext<CounterValue>("Counter");
export function CounterProvider({ children }: { children: ReactNode }) {
const [count, setCount] = useState(0);
const value: CounterValue = {
count,
increment: () => setCount((c) => c + 1),
};
return (
<CounterContextProvider value={value}>{children}</CounterContextProvider>
);
}
export { useCounter };This version uses <Context.Provider> as the component. On React 19 and later you can also render the context object directly as <Context value={...}>. Check your React version before using that form.
Edge cases and common errors
Legitimate `null` values
The null check cannot tell "no provider" from "the provider's value is null". Do not put null in T when using this pattern. If the value can be absent, wrap it in an object, such as { user: User | null }.
Unstable value objects
In the provider above, value={{ theme, setTheme }} creates a new object on every render. Every consumer then re-renders whenever the provider re-renders, even if nothing changed. For providers that re-render often, memoize the value.
import { useMemo, useState, type ReactNode } from "react";
// Uses ThemeContext, Theme and ThemeContextValue from earlier.
export function MemoThemeProvider({ children }: { children: ReactNode }) {
const [theme, setTheme] = useState<Theme>("light");
const value = useMemo<ThemeContextValue>(
() => ({ theme, setTheme }),
[theme],
);
return (
<ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>
);
}setTheme from useState is stable, so it does not need to be in the dependency list.
Reducer-based contexts
For complex state, put useReducer in the provider and share state and dispatch. Type dispatch as Dispatch<Action>, imported from react. Many teams split this into two contexts, one for state and one for dispatch. Components that only dispatch then avoid re-rendering when the state changes.
Mismatched type arguments
If you write createContext<ThemeContextValue>(null), strict mode reports that null is not assignable to the type. Do not silence this with null as unknown as ThemeContextValue. That removes the guarantee the whole pattern exists to provide.
Circular file imports
Keep the context, provider, and hook in one file. Splitting them across files that import each other can produce a context that is undefined at runtime in some bundlers.
Summary of the pattern
- Define an interface for the value.
- Create the context as
createContext<Value | null>(null). - Write a provider that owns the state and passes a value matching the interface.
- Export a custom hook that throws on
nulland returnsValue. - Keep the raw context private.
Exercises
Exercise
A teammate writes const AuthContext = createContext<AuthValue>(null); with strict on. What error appears, and what is the recommended fix that keeps consumers free of null checks?
Show answer
TypeScript reports that null is not assignable to AuthValue. Change the context to createContext<AuthValue | null>(null), then export a useAuth hook that calls useContext, throws an Error if the result is null, and otherwise returns it with type AuthValue. Consumers call useAuth() and get a non-null value.
Exercise
Your context value is { user: User | null }. Is it safe to use the null-default pattern with T set to this object type? Explain why.
Show answer
Yes. The hook checks whether the whole context value is null, which only happens with no provider. The user field is inside the object, so a signed-out user ({ user: null }) is not confused with a missing provider. The problem would arise only if T itself included null.
Exercise
Why does useState("light") inside a theme provider cause a type error when you pass setTheme to a context value typed (theme: Theme) => void, and how do you fix it?
Show answer
TypeScript infers string from "light", so setTheme accepts any string. Its parameter type is wider than Theme, and the error comes from the state's inferred type not matching Theme where the value is read (theme: string is not assignable to Theme). Fix it with useState<Theme>("light").