Sub topic 11
Typing useReducer with action unions
This chapter assumes you know basic React (function components, props, state, JSX) and TypeScript fundamentals (interfaces, type aliases, unions, generics). You should also be able to run a TypeScript project in Vite or Next.js with strict turned on.
useState is enough for a single value. When state has several fields, or when many events change it in related ways, useReducer keeps the update logic in one place. TypeScript adds a second benefit. If you describe every possible action as a union, the compiler rejects unknown actions and shows each case only the fields that action carries.
The working model
A reducer is a pure function with this shape:
(state: State, action: Action) => StateReact calls it with the current state and the action you passed to dispatch. It returns the next state. Three types do the work:
Statedescribes the data the reducer holds.Actionis a union of every event the reducer understands.- The return type of the reducer is
State, so every branch must produce a complete, valid state.
useReducer infers its own types from the reducer function. You rarely write type arguments on the hook itself.
Defining state and the action union
The example below is a counter. Each action is an object type with a literal type property. That property is the discriminant, the field TypeScript uses to tell the union members apart.
import { useReducer } from "react";
type State = { count: number };
type Action =
| { type: "increment" }
| { type: "decrement" }
| { type: "set"; value: number };
function reducer(state: State, action: Action): State {
switch (action.type) {
case "increment":
return { count: state.count + 1 };
case "decrement":
return { count: state.count - 1 };
case "set":
return { count: action.value };
}
}
export function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<button onClick={() => dispatch({ type: "increment" })}>
{state.count}
</button>
);
}Several things happen here without any extra annotations.
stateis inferred asState, anddispatchis inferred asDispatch<Action>.- The initial value
{ count: 0 }is checked againstState. A missing or misspelled field is an error. - Inside
case "set", TypeScript narrowsactionto{ type: "set"; value: number }. That is whyaction.valueis allowed there. Incase "increment",action.valuewould be an error.
What the compiler rejects
These calls fail to compile:
dispatch({ type: "reset" }); // "reset" is not in the union
dispatch({ type: "set" }); // property 'value' is missing
dispatch({ type: "increment", value: 3 }); // 'value' does not exist on this actionThe second and third errors show why a union of object types beats one loose type such as { type: string; value?: number }. With the loose type, dispatch({ type: "set" }) compiles, and action.value is number | undefined in every branch, so you need checks everywhere.
Exhaustiveness: the return type and `never`
The reducer above has no default branch and still compiles. With strict on, TypeScript sees that the switch covers all three members, so the end of the function is unreachable and every path returns a State.
Now add a new action to the union and forget the matching case:
type Action =
| { type: "increment" }
| { type: "decrement" }
| { type: "set"; value: number }
| { type: "reset" };The reducer now has a path that returns nothing. TypeScript reports that the function lacks an ending return statement and its return type does not include undefined. The compiler found the missing case for you.
This check depends on your settings and on how you write the reducer. Two points to know:
- It only works because the return type is annotated as
State. If you leave the annotation off, the inferred return type becomesState | undefinedand the error disappears. Always annotate reducer return types. - It relies on
strict(specificallystrictNullChecks). The chapter on setup covers thetsconfig.jsonthat enables it.
For a more explicit guard, add a default branch that assigns the action to never:
function assertNever(value: never): never {
throw new Error(`Unhandled action: ${JSON.stringify(value)}`);
}
function reducer(state: State, action: Action): State {
switch (action.type) {
case "increment":
return { count: state.count + 1 };
case "decrement":
return { count: state.count - 1 };
case "set":
return { count: action.value };
case "reset":
return { count: 0 };
default:
return assertNever(action);
}
}If a member of Action has no case, action in the default branch is not never, and the call to assertNever is a compile error. The function also throws at runtime, which helps if an untyped caller (for example, JavaScript code or a parsed message) sends an action you did not expect.
Choosing the discriminant and payload shape
The field name type is a convention from Redux, and it works well. Any literal-typed property can be the discriminant, but keep one name across all actions in a reducer.
Keep payloads small and put them in named fields:
type Action =
| { type: "added"; item: Item }
| { type: "removed"; id: number }
| { type: "cleared" };Name actions after what happened (added, removed) rather than the state change you want (setItems). Event-style names keep the reducer in charge of how state changes, and they stay stable when the state shape changes.
Typing state that has several shapes
State can also be a union. This is useful for loading flows where some fields only exist in some phases.
import { useReducer } from "react";
interface User {
id: number;
name: string;
}
type FetchState =
| { status: "idle" }
| { status: "loading" }
| { status: "success"; user: User }
| { status: "error"; message: string };
type FetchAction =
| { type: "start" }
| { type: "succeed"; user: User }
| { type: "fail"; message: string };
function fetchReducer(state: FetchState, action: FetchAction): FetchState {
switch (action.type) {
case "start":
return { status: "loading" };
case "succeed":
return { status: "success", user: action.user };
case "fail":
return { status: "error", message: action.message };
}
}
export function UserLoader() {
const [state, dispatch] = useReducer(fetchReducer, { status: "idle" });
return (
<div>
<button onClick={() => dispatch({ type: "start" })}>Load</button>
<button
onClick={() => dispatch({ type: "succeed", user: { id: 1, name: "Ada" } })}
>
Succeed
</button>
<button onClick={() => dispatch({ type: "fail", message: "Network down" })}>
Fail
</button>
{state.status === "success" && <p>{state.user.name}</p>}
{state.status === "error" && <p>{state.message}</p>}
</div>
);
}The same narrowing that works on actions works on state. state.user is only available after you check state.status === "success". The state can never be "success" without a user, so you cannot render a user that is not there.
The initial-state literal gotcha
In useReducer(fetchReducer, { status: "idle" }), TypeScript checks the literal against the reducer's State type, so "idle" is not widened to string. If you build the initial state in a separate variable, the literal can widen:
const initial = { status: "idle" }; // type: { status: string }
const initialTyped: FetchState = { status: "idle" }; // type: FetchStatePassing initial to useReducer fails to compile, because { status: string } is not assignable to FetchState. Annotate the variable, or use as const.
Lazy initialization
useReducer accepts a third argument, an init function. It receives the second argument and returns the starting state. React calls it once.
import { useReducer } from "react";
type State = { count: number };
type Action = { type: "increment" } | { type: "reset"; to: number };
function init(start: number): State {
return { count: start };
}
function reducer(state: State, action: Action): State {
switch (action.type) {
case "increment":
return { count: state.count + 1 };
case "reset":
return init(action.to);
}
}
export function ResettableCounter({ start }: { start: number }) {
const [state, dispatch] = useReducer(reducer, start, init);
return (
<button onClick={() => dispatch({ type: "reset", to: start })}>
{state.count}
</button>
);
}Here the second argument has type number, and init converts it to State. TypeScript infers both from init's signature.
Passing dispatch to children
Child components often need to dispatch. Type the prop with Dispatch from React:
import type { Dispatch } from "react";
type Action = { type: "increment" } | { type: "decrement" };
export function Controls({ dispatch }: { dispatch: Dispatch<Action> }) {
return (
<>
<button onClick={() => dispatch({ type: "decrement" })}>-</button>
<button onClick={() => dispatch({ type: "increment" })}>+</button>
</>
);
}dispatch keeps the same identity between renders, so passing it down does not cause extra renders on its own. In a real project, export Action from the file that defines the reducer so the child imports one type instead of redeclaring it.
If a child only needs to trigger one event, pass a narrower callback such as onIncrement: () => void. This keeps the child independent of the reducer.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `action.value` is an error inside a `case` | The case label does not match the member that has `value`, or the union members lack a literal `type` | Use literal types such as `"set"`, not `string`, for the discriminant |
| Reducer with no error when a case is missing | Return type not annotated, or `strict` is off | Annotate `: State` and enable `strict` |
| `dispatch({ type: "x" })` accepted when it should fail | Action typed as `{ type: string }` | Use a union of literal-typed members |
| Initial state not assignable to `State` | Literal widened in a separate variable | Annotate the variable with `State` |
| State is mutated and the UI does not update | Reducer changes `state` in place and returns it | Return a new object, for example `{ ...state, count: 1 }` |
When to choose `useReducer` over `useState`
Choose useReducer when:
- Several state fields change together, or the next value depends on a mix of old fields.
- Many event handlers perform variants of the same update, and you want the rules in one function.
- You want to test the update logic as a plain function, without rendering.
- State is a union of phases, as in the fetch example.
Stay with useState when you have one independent value, such as a toggle or a text input. A reducer there adds types and code with no benefit.
Exercise
A reducer handles { type: "add"; item: string } and { type: "clear" }. You add { type: "remove"; index: number } to the Action union but forget to add a case. The reducer has an annotated return type of string[] and strict is on. What does the compiler report, and what would change if you removed the return type annotation?
Show answer
With the annotation, TypeScript reports that the function lacks an ending return statement and its return type does not include undefined, because a remove action reaches the end of the switch without returning. Without the annotation, the inferred return type becomes string[] | undefined, so the reducer itself compiles. The error then shows up where the result is used, for example in the useReducer call, which may report a type mismatch or may not report anything useful. Annotating the return type, or adding a default branch with assertNever, keeps the error at the reducer.
Exercise
Write the Action union and reducer for a todo list. State is { todos: { id: number; text: string; done: boolean }[] }. Support adding a todo with text, toggling a todo by id, and clearing all todos. Which fields does each action carry?
Show answer
```ts is not needed here; the types are: type Action = { type: "add"; id: number; text: string } | { type: "toggle"; id: number } | { type: "clear" }. The reducer returns, for "add", { todos: [...state.todos, { id: action.id, text: action.text, done: false }] }. For "toggle", it returns { todos: state.todos.map((t) => t.id === action.id ? { ...t, done: !t.done } : t) }. For "clear", it returns { todos: [] }. The "add" action carries id and text, "toggle" carries only id, and "clear" carries nothing besides type.