Lesson 2 of 9 · 24m
Discriminated Unions for Real State
Model loading, empty, success, failure, and editor workflows as state machines so impossible screens cannot compile.
Most React state bugs are not async bugs. They are modeling bugs. The screen is simultaneously loading and erroring, has data and is empty, or is submitting after it already succeeded — because three booleans were allowed to drift independently.
Replace boolean piles with one state value
type UserState =
| { status: "loading" }
| { status: "error"; message: string }
| { status: "empty" }
| { status: "success"; user: User };The status field is the discriminant: a literal tag TypeScript can use to narrow the union.
function UserPanel({ state }: { state: UserState }) {
switch (state.status) {
case "loading":
return <Spinner label="Loading user" />;
case "error":
return <Alert tone="danger">{state.message}</Alert>;
case "empty":
return <EmptyState title="No user selected" />;
case "success":
return <UserDetails user={state.user} />;
}
}Inside the success branch, state.user exists. Inside loading, it does not. The compiler enforces the thing product managers assume is obvious.
Transitions belong in one place
For interactive state, use useReducer and make the events explicit:
type Action =
| { type: "submit" }
| { type: "success"; user: User }
| { type: "failure"; message: string }
| { type: "reset" };
function reducer(state: UserState, action: Action): UserState {
switch (action.type) {
case "submit":
return { status: "loading" };
case "success":
return { status: "success", user: action.user };
case "failure":
return { status: "error", message: action.message };
case "reset":
return { status: "empty" };
}
}The benefit is not ceremony. It is that state transitions become reviewable. You can ask, "Can we go from error directly to success?" and answer by reading one function.
Exhaustiveness is the point
Add a compile-time check when a case must never be missing:
function assertNever(value: never): never {
throw new Error(`Unhandled state: ${JSON.stringify(value)}`);
}If a new status is added later, an unhandled switch stops compiling. That beats finding out from a blank production screen.
Field notes
- Keep the discriminant name consistent (
statusorkind) across the app. - Do not put derived UI facts like
isEmptyinto state; derive them in render. - Union fields can differ per branch — that is the feature, not a problem to normalize away.
- A reducer is overkill for two independent toggles and exactly right for workflow state.
Was this lesson helpful?