Sub topic 8
Modeling the flow as a state machine
This chapter assumes you know basic TypeScript (union types, switch, spreading objects) and the idea of a reducer, a function that takes the current state and an action and returns the next state. It also assumes you have seen the form state from the earlier chapters: values, touched, dirty, and errors.
Why a multi-step form needs explicit state
A one-page form can get by with a pile of variables. A multi-step form cannot. It has to answer questions like these:
- Which step is the user on?
- May they move forward?
- What happens to their answers when they go back?
- What does the browser's back button do?
If the answers are scattered across click handlers, you get bugs like these: a user reaches the review step with an invalid email, a hidden step's data is submitted, or a double click skips a step.
A state machine fixes this by making the flow a closed set of rules. At any moment the form is in exactly one state. Only a fixed set of events can change that state. Each event has a defined result. Anything not listed cannot happen.
States, events, and guards
Three terms carry most of the model.
- A state is where the user is. In our flow it is one of
account,details, orreview. - An event is something that happens: the user edits a field, presses Next, or presses Back.
- A guard is a condition that must hold for a transition to occur. Here the guard on Next is that the current step validates.
The following table lists the transitions for a three-step flow.
| From state | Event | Guard | To state |
|---|---|---|---|
| account | next | account fields valid | details |
| account | next | account fields invalid | account (errors set) |
| details | next | details fields valid | review |
| details | back | none | account |
| review | back | none | details |
| any | change | none | same state (value updated) |
The table shows two properties. Next is a conditional transition that can loop back to the same state. Back has no guard, because leaving a step must never be blocked or lose data.
Writing the machine as a pure reducer
A reducer fits this model well. It is a pure function, so it has no side effects and the same input always gives the same output. That makes every transition testable without a browser.
The code below defines the whole machine and then drives it by hand. You can run it with any TypeScript runner, such as npx tsx.
const steps = ["account", "details", "review"] as const;
type StepId = (typeof steps)[number];
type State = {
step: StepId;
values: Record<string, string>;
errors: Record<string, string>;
};
type Action =
| { type: "change"; name: string; value: string }
| { type: "next" }
| { type: "back" };
function validate(step: StepId, values: Record<string, string>): Record<string, string> {
const errors: Record<string, string> = {};
if (step === "account" && !values.email?.includes("@")) {
errors.email = "Enter an email address in the format [email protected].";
}
if (step === "details" && !values.name?.trim()) {
errors.name = "Enter your full name.";
}
return errors;
}
function reducer(state: State, action: Action): State {
const index = steps.indexOf(state.step);
switch (action.type) {
case "change":
return { ...state, values: { ...state.values, [action.name]: action.value } };
case "next": {
const errors = validate(state.step, state.values);
if (Object.keys(errors).length > 0) return { ...state, errors };
return { ...state, errors: {}, step: steps[Math.min(index + 1, steps.length - 1)] };
}
case "back":
return { ...state, errors: {}, step: steps[Math.max(index - 1, 0)] };
}
}
let state: State = { step: "account", values: {}, errors: {} };
state = reducer(state, { type: "next" });
console.log(state.step, state.errors); // account { email: "Enter an email address..." }
state = reducer(state, { type: "change", name: "email", value: "[email protected]" });
state = reducer(state, { type: "next" });
console.log(state.step); // details
state = reducer(state, { type: "back" });
console.log(state.step, state.values.email); // account [email protected]Three design choices in this reducer are worth noting.
- Values live outside the step. There is one
valuesobject for the whole flow, not one per step. Going back therefore cannot discard anything, because no transition deletes values. - Errors belong to the current step only. Both
nextandbackreseterrors. Stale errors from a step you left would otherwise reappear when you return, before the user has done anything. - Forward moves are clamped.
Math.minandMath.maxkeep the index inside the array, so anexton the last step stays on the last step. Submission is a separate concern, covered in the review chapter.
Keep derived facts out of state
State should hold only what cannot be computed. Whether the user is on the first step, how far along the progress bar is, and whether the Back button should be shown can all be derived from step. Storing them separately invites contradictions, such as isFirst: true while step is details.
const steps = ["account", "details", "review"] as const;
function progress(step: (typeof steps)[number]) {
const index = steps.indexOf(step);
return {
isFirst: index === 0,
isLast: index === steps.length - 1,
label: `Step ${index + 1} of ${steps.length}`,
};
}
console.log(progress("details").label); // Step 2 of 3Making impossible states impossible
The State type above still allows combinations the machine never produces. For example, step: "account" with an error keyed name type-checks fine. For a small form this is acceptable, since the reducer is the only writer. For a larger flow you can tighten the types so that each state carries only what it needs.
Submission is the clearest case. Adding a boolean isSubmitting next to step allows isSubmitting: true on the account step, which makes no sense. A better design adds a status that is a union ("editing" | "submitting" | "failed" | "done"), so only one value can be true at a time. The async chapter builds on that.
Conditional steps and the skipping problem
The linear index + 1 rule breaks when a step is conditional. Suppose the shipping step applies only when the user chooses delivery. Moving forward from account should skip shipping when the user picks pickup, and moving back from review should skip it as well.
Put the skip rule in the flow definition and compute neighbors by searching in a direction.
type Values = Record<string, string>;
type StepDef = { id: string; skipWhen?: (values: Values) => boolean };
const flow: StepDef[] = [
{ id: "account" },
{ id: "shipping", skipWhen: (v) => v.delivery === "pickup" },
{ id: "review" },
];
function neighbor(from: string, values: Values, direction: 1 | -1): string {
const start = flow.findIndex((s) => s.id === from);
if (start === -1) return flow[0].id;
for (let i = start + direction; i >= 0 && i < flow.length; i += direction) {
const step = flow[i];
if (!step.skipWhen || !step.skipWhen(values)) return step.id;
}
return from;
}
console.log(neighbor("account", { delivery: "pickup" }, 1)); // review
console.log(neighbor("account", { delivery: "ship" }, 1)); // shipping
console.log(neighbor("review", { delivery: "pickup" }, -1)); // accountThe same visibility rules must drive validation and submission. The conditional fields chapter showed activeValues, which keeps hidden answers out of the payload. If the user chose delivery, entered an address, then switched to pickup, the address remains in values (so switching back restores it) but must not be sent.
Common errors
- Deriving the step from the URL and the state separately. If you sync the step to the URL for deep links and the back button, pick one source of truth. Let the state drive the URL, and on load, validate the URL's step against the state. A user who opens
/signup/reviewwith an empty form should land on the first incomplete step, not on a review of nothing. - Validating only the current step. The guard on Next checks one step. A user who jumps via the URL, or edits an earlier answer after reaching review, can still produce invalid data. Re-run validation for every active step before the final submit.
- Letting
changeclear later steps. Changing an answer on step 1 may make step 3 answers meaningless. Decide deliberately whether to clear them. Clearing silently loses data, while keeping them risks submitting inconsistent answers. Keeping them and validating at review usually serves users best. - Putting side effects in the reducer. Saving a draft, sending analytics, or moving focus does not belong in a pure function. Run those after the state changes, in an effect that reacts to the new state.
- Treating Back as a form of cancel. Back changes the step only. Anything that discards data should be a separate, explicit action with confirmation.
Testing the machine
Because the reducer is pure, tests are short and need no DOM. Cover each row of the transition table, plus the edge cases: Next on the last step, Back on the first step, and Back after a failed Next. Check that errors is empty after Back and that values is unchanged. These tests fail loudly when someone adds a step and forgets a transition.
Exercise
In the reducer above, a user on the details step presses Next with an empty name, sees the error, and then presses Back. What are step, errors, and values afterward, and why is that the right behavior?
Show answer
step is account. errors is {}, because the back case resets errors so the previous step does not show messages from the step the user left. values is unchanged, because no transition removes values, so everything the user entered on account is still there. Back is unguarded and non-destructive by design.
Exercise
Using the neighbor function, what step does neighbor("account", { delivery: "pickup" }, 1) return, and why must the same skipWhen rule also be applied when computing the progress label "Step N of M"?
Show answer
It returns review, because shipping is skipped when delivery is pickup. The progress label must use the same rule so that M counts only the active steps. Otherwise the user sees "Step 2 of 3" on the review step, or a step count that jumps, which is inconsistent with the steps they actually visit.