Sub topic 3
Modeling flow state
This chapter covers the data structure behind a guided flow. It assumes you can read TypeScript, know how form fields and their values work, and understand that application state is data your UI renders from. The earlier chapters introduced the purpose of a flow and how to split input into steps. Here you decide what the flow must remember, and where.
What the state has to answer
At any moment a flow must be able to answer four questions:
- Which step is the user on?
- What have they entered so far?
- How did they get here, so that Back returns to the right place?
- What, if anything, is wrong with the current step?
Each question maps to one field of the state. If you can't point to the field that answers a question, the answer is probably hidden somewhere less reliable, such as a DOM node, a component's local variable, or a URL fragment. Hidden state is the usual source of flows that lose answers on Back or show stale errors.
The four fields
type Data = Record<string, string>;
type FlowState = {
current: string;
history: string[];
data: Data;
errors: string[];
};
function createInitialState(startId: string, data: Data = {}): FlowState {
return { current: startId, history: [], data: { ...data }, errors: [] };
}
function setField(state: FlowState, name: string, value: string): FlowState {
return { ...state, data: { ...state.data, [name]: value } };
}| Field | Answers | Changes when |
|---|---|---|
| `current` | Where is the user? | A step transition succeeds |
| `history` | How did they get here? | The user advances (push) or goes back (pop) |
| `data` | What have they entered? | The user edits any field |
| `errors` | What must they fix? | Validation runs, or the step changes |
Two design rules sit behind this shape.
- State is plain data. It contains strings, arrays, and objects. It has no functions, no component references, and no class instances. Plain data can be logged, compared in tests, and converted with
JSON.stringify, which later makes saving drafts straightforward. - State is separate from the flow definition. The
stepstable holds functions (validate,next) and never changes at runtime. The state holds only what the user has done. You can load a saved state into any copy of the definition without serializing code.
Keep position and data apart
The most common modeling mistake is to store answers inside the step that collected them, for example state.steps.account.email. It looks tidy, but it causes three problems.
- Branches can share answers. A later step may need the account type chosen in an earlier one, so every step would need to read other steps' storage.
- Steps can be added, renamed, or removed as the flow evolves. Answers keyed by step id then need migrating. Answers keyed by field name usually don't.
- The review step has to merge many small objects. With one flat
datarecord it reads a single object.
So data is one flat record keyed by field name, and current is only a step id. Field names must be unique across the whole flow. Two steps that both want a field called name need contactName and companyName, or a naming convention such as billing.name.
Store raw input as strings
Form controls produce strings, including number inputs and dates. Keeping data as Record<string, string> means the state holds exactly what the user typed. If you store a parsed number, "12abc" becomes NaN or 12, and the user's input has been silently altered. Validate the string while the user is working, and convert to numbers, dates, or booleans once, at submission.
A field the user has never touched is absent from data. An empty field is "". These are different states, and validators that read d.email ?? "" treat them the same, which is usually what you want.
Updating state without mutation
Every change returns a new object. setField above copies data and replaces one key. It never writes to the old state.
This costs a little allocation and buys three things.
- A UI framework that compares references can tell what changed.
- You can keep the previous state, which is useful for undo and for debugging.
- Tests can assert on the input state afterward to confirm it wasn't touched.
Note what setField does not do. It does not validate, and it does not clear errors. Typing in a field is not an attempt to advance, so errors from the last attempt stay visible until the user tries again or leaves the step. Decide this on purpose. If you instead clear errors on every keystroke, a screen reader user may lose the message while still reading it. Accessibility is covered in a later chapter.
The history stack
history holds the ids of the steps the user has passed through, oldest first. It does not include current. The invariants are:
advancepushes the oldcurrentontohistory, then setscurrentto the next id.backpops the last id and makes itcurrent.- The first step has an empty
history, so Back has nowhere to go.
Why a stack and not "the previous step by position"? Because the previous step depends on the path. In the account flow, a personal user goes from account straight to review. A business user goes account, company, review. From review, Back must return to company for one user and to account for the other. A stack records what actually happened, so Back needs no knowledge of the branching rules.
The same stack gives you a free step counter. With history.length + 1 the user sees "Step 1", "Step 2" and so on, without the flow having to know its total length. A later chapter returns to progress indication.
Stale answers after a branch changes
History is a record of the past. The data in data can outlive the path that produced it. Consider this sequence:
- The user picks
businessand enters a company name. - They go back and switch to
personal. data.companystill holds the old company name.
The state is not wrong, because keeping the answer means the user doesn't lose their typing if they switch back. But if submission sends every key in data, the server receives a company name for a personal account. The fix is to derive the active path from the current answers and collect only fields belonging to steps on that path.
type Step = {
id: string;
validate(data: Data): string[];
next(data: Data): string | null;
};
function activePath(
startId: string,
data: Data,
steps: Record<string, Step>
): string[] {
const path: string[] = [];
let id: string | null = startId;
while (id !== null && !path.includes(id)) {
const step = steps[id];
if (!step) break;
path.push(id);
id = step.next(data);
}
return path;
}
function collectSubmission(
startId: string,
data: Data,
steps: Record<string, Step>,
fieldsByStep: Record<string, string[]>
): Data {
const result: Data = {};
for (const id of activePath(startId, data, steps)) {
for (const field of fieldsByStep[id] ?? []) {
if (field in data) result[field] = data[field];
}
}
return result;
}activePath walks forward from the start by calling each step's next with the current data. The path.includes(id) check stops the walk if a definition mistake creates a cycle, and the if (!step) break guard stops it at an unknown id. Both turn a would-be infinite loop or crash into a short path that tests can catch.
There are two ways to handle stale answers, and each has costs.
| Approach | Behavior | Trade-off |
|---|---|---|
| Keep everything, filter at submit | Switching back restores earlier answers | Needs the `fieldsByStep` map and a path walk |
| Delete fields when the branch changes | `data` always matches the path | The user loses input if they change their mind |
Keeping and filtering is friendlier. Deleting is simpler to reason about. Pick one and apply it everywhere.
Where errors live
errors is a list of messages for the current step. It is replaced each time validation runs and reset to [] on every successful transition and on Back. A step the user is returning to should open clean, since they already passed it.
A single list is enough when a step has one or two fields. When you need to attach messages to specific inputs, change the type to Record<string, string[]> keyed by field name. This is a bigger change than it looks. Every consumer that reads errors.length must change, so choose before you build many steps. Showing errors is covered in a later chapter.
Do not store errors for steps other than the current one. They are derived from data by calling validate, so storing them creates a second copy that can fall out of date.
Rejecting impossible states
The type FlowState allows values that make no sense. current could be "payment" in a flow that has no such step, or history could contain current itself. TypeScript can't rule these out without making ids a union of literals, which is awkward for definitions loaded from data. A small consistency check catches them, especially after loading a saved draft from an older version of the flow.
function checkState(state: FlowState, steps: Record<string, Step>): string[] {
const problems: string[] = [];
if (!(state.current in steps)) {
problems.push("Unknown current step: " + state.current);
}
for (const id of state.history) {
if (!(id in steps)) problems.push("Unknown step in history: " + id);
}
if (state.history.includes(state.current)) {
problems.push("Current step also appears in history.");
}
return problems;
}The last rule assumes a flow without loops. If your flow lets users revisit a step, drop that rule.
Putting it together
This script uses the steps from the previous chapter and runs as written with npx tsx, assuming the code blocks above are in the same file. It shows that state survives a JSON round trip and that stale answers are filtered out.
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 },
};
const fieldsByStep: Record<string, string[]> = {
account: ["email", "accountType"],
company: ["company"],
review: [],
};
let state = createInitialState("account");
state = setField(state, "email", "[email protected]");
state = setField(state, "accountType", "business");
state = setField(state, "company", "Analytical Engines Ltd");
state = setField(state, "accountType", "personal");
const restored: FlowState = JSON.parse(JSON.stringify(state));
console.log(checkState(restored, steps));
console.log(activePath("account", restored.data, steps));
console.log(collectSubmission("account", restored.data, steps, fieldsByStep));The output is an empty problem list, then [ 'account', 'review' ], then an object with only email and accountType. The company name is still in restored.data but is not submitted.
Common errors
- Using an array index as the position. An index shifts when a step is inserted or a branch hides one. Step ids stay stable.
- Holding data in component state per step. When a step unmounts after Next, its component state is lost, so Back shows empty fields. Keep data in the flow state and let each step render from it.
- Mutating
historyin place.pushandpopchange the array that earlier state objects still point to. Use spread andslice. - Parsing values as they are typed. Store strings and parse at submission.
- Storing derived values. Step count, "is this the last step", and the active path can all be computed from the state. A stored copy can disagree with it.
Exercise
A user on the business path goes account, company, review, then presses Back twice and changes the account type to personal, then advances. What are current and history on arrival at review, and does data.company still hold the old name?
Show answer
After two Back presses, current is account and history is empty. Advancing validates account, calls next, which returns review for personal, and pushes account. So current is review and history is ["account"]. company is never visited, so it isn't in history. data.company still holds the old name, because nothing removes it. Filtering through activePath and collectSubmission keeps it out of the submitted data.
Exercise
Why does FlowState keep errors as only the current step's messages instead of a map of errors for every step?
Show answer
Errors are derived from data by running validate. A stored map for other steps would be a second copy that goes stale as soon as the user edits an answer. Keeping only the current step's errors, and clearing them on every transition, avoids that.