Sub topic 3
Modeling flow state
This chapter assumes you can read TypeScript, know how form fields and values work, and understand that application state is data your UI renders from. It covers the state a flow needs and the functions that change it. Navigation, validation, and branching each get their own chapter, so here they appear only where the state shape depends on them.
What the flow must remember
A guided flow answers four questions at any moment:
- Which step is the user on?
- What have they entered so far?
- How did they get here?
- What is wrong with the current step, if anything?
Each question maps to one field. If you cannot point to where a fact lives, the UI will end up storing it in several places, and those places will disagree.
type Data = Record<string, string>;
type FlowState = {
current: string;
history: string[];
data: Data;
errors: string[];
};| Field | Holds | Why it exists |
|---|---|---|
| `current` | The id of the active step | Decides which step to render |
| `data` | All answers collected so far | One store shared by every step |
| `history` | Ids of steps already visited, in order | Lets Back return to the step the user came from |
| `errors` | Messages for the current step | Lets the UI show what to fix |
Steps as data
The flow needs a definition of its steps that is separate from the state. A step declares how to validate its own fields and which step comes next. The state records where the user is. The step definitions describe what is possible.
type Step = {
id: string;
validate(data: Data): string[];
next(data: Data): string | null;
};
const steps: Record<string, Step> = {
account: {
id: "account",
validate: (d) =>
/^\S+@\S+\.\S+$/.test(d.email ?? "") ? [] : ["Enter a valid email address."],
next: (d) => (d.accountType === "business" ? "company" : "review"),
},
company: {
id: "company",
validate: (d) => ((d.company ?? "").trim() ? [] : ["Enter your company name."]),
next: () => "review",
},
review: {
id: "review",
validate: () => [],
next: () => null,
},
};The next function returns the id of the following step, or null when the flow ends. Branching lives here, in data, so you will not find if statements spread across components. The account step sends business users to company and everyone else straight to review.
Why history is a stack
You might try to compute the previous step by looking at the current one. That fails once the flow branches. A user on review may have arrived from account or from company, and nothing in review tells you which.
Store the path instead. Each time the user moves forward, push the step they left onto history. Back pops the last entry. The top of the stack is always the step the user actually came from.
Transitions as pure functions
Write each change to the state as a function that takes the old state and returns a new one. The function never edits its input. This keeps the logic easy to test and works with any UI framework, because the framework only needs to store whatever the function returns.
function advance(state: FlowState, steps: Record<string, Step>): FlowState {
const step = steps[state.current];
const errors = step.validate(state.data);
if (errors.length > 0) return { ...state, errors };
const nextId = step.next(state.data);
if (nextId === null) return { ...state, errors: [] };
return {
...state,
current: nextId,
history: [...state.history, state.current],
errors: [],
};
}
function back(state: FlowState): FlowState {
const previous = state.history[state.history.length - 1];
if (previous === undefined) return state;
return {
...state,
current: previous,
history: state.history.slice(0, -1),
errors: [],
};
}Two details are worth noting:
advanceleavescurrentandhistoryunchanged when validation fails, and only setserrors. The user stays put.- Both functions reset
errorswhen the step changes, so messages from one step never appear on another.
Common mistakes
- Keeping data per step. If each step holds its own copy of its fields, Back can lose input and later steps cannot read earlier answers. Keep one
dataobject for the whole flow. - Storing a step number instead of an id. Numbers break when a branch adds or removes steps. Ids stay stable.
- Deriving Back from a rule. As shown above, a rule cannot know which branch the user took. Use
history. - Mutating state in place. Pushing onto
historydirectly can leave a UI that compares references showing stale content.
Initial state
A new flow starts on the first step, with no history, no data, and no errors.
const initialState: FlowState = {
current: "account",
history: [],
data: {},
errors: [],
};Because history is empty here, back(initialState) returns the state unchanged. The Back button can be hidden or disabled based on history.length === 0.
Exercise
A user is on review with history equal to ["account", "company"]. They press Back twice. What are current and history after each press?
Show answer
After the first press, current is company and history is ["account"]. After the second press, current is account and history is []. A third press returns the state unchanged because history is empty.
Exercise
Why does advance return { ...state, errors } instead of changing current when validation fails?
Show answer
The user must stay on the step until its input is valid. Returning the same current and history with the new errors keeps them there and gives the UI messages to display.