Sub topic 7
Branching on earlier answers
This chapter assumes you have read the earlier chapters on flow state, navigation, and per-step validation. You should be comfortable with a FlowState that holds a current step id, a history stack, and collected data. You should also know how advance and back use that state.
A branch is a point where the next step depends on what the user already said. A business account sees a company step. A personal account skips it. This chapter shows how to keep that logic in one place, how it interacts with Back, and which errors appear when answers change.
Where branching logic should live
The simplest way to branch is an if inside the code that renders or advances each screen. This works for one branch. With three or four, the rules spread across the UI, and nobody can answer the question "which steps can follow this one?" without reading everything.
The alternative is to make each step declare its own successor. Each step has a next function that takes the collected data and returns the id of the next step, or null when the flow is finished.
type Data = Record<string, string>;
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 branch lives in account.next. The advance function does not know that a branch exists. It calls step.next(state.data) and goes where the answer points. Adding a new branch means editing one step, and the flow engine stays unchanged.
Rules for writing a next function
A next function is a pure decision. Follow these rules to keep it predictable.
- Read only from
data. Do not read the clock, the network, or global state. The same data must always produce the same result. This makes the flow testable and lets you recompute a path later. - Return a step id that exists in the step table, or
null. A typo such as"compnay"fails at runtime on the lookup. In TypeScript, you can narrow the ids with a union type so the compiler catches this. - Always handle the unexpected value. In
account.next, anything other than"business"goes toreview. That default means a missing or unknownaccountTypestill produces a valid path. - Do not mutate
data. Branching decides where to go. It does not change answers.
A typed id union looks like this:
type StepId = "account" | "company" | "review";
type TypedStep = {
id: StepId;
validate(data: Data): string[];
next(data: Data): StepId | null;
};With this type, returning "compnay" is a compile error. The cost is that the union must be updated when you add a step.
What Back does after a branch
Branching makes Back harder than it looks. If Back recomputed the previous step from the data, it would have to run the logic in reverse, and several steps can lead to the same place. In the example above, review can be reached from account or from company. Looking at the data alone, you cannot tell which one the user came from.
The history stack solves this. Every time advance moves forward, it pushes the step the user left. Back pops the last entry, so it returns to the step the user actually visited.
type FlowState = {
current: string;
history: string[];
data: Data;
errors: string[];
};
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: [],
};
}Here is a trace for a business user, ending on Back.
| Action | current | history |
|---|---|---|
| Start | account | (empty) |
| Advance (business) | company | account |
| Advance | review | account, company |
| Back | company | account |
| Back | account | (empty) |
A personal user goes account, then review. Back from review returns to account, skipping company, because company was never pushed.
The stale answer problem
The history stack records where the user went. It does not record whether the answers are still valid for that path. This leads to the most common branching bug.
Suppose a user picks "business", types a company name, and moves to review. They go Back twice to account and change the type to "personal". The company value is still in data. If the review step or the submit code reads every key in data, it sends a company name for a personal account.
There are two further problems with the history itself. The stack still holds whatever path the user took before the change. After they edit accountType and advance, the new next result may differ from the old one, but the history entries for the old path are still there if the user did not pop them. In the code above this is safe when the user reaches account by Back, because Back pops entries. It is not safe if your UI lets users jump straight to an earlier step, for example by clicking a step in a sidebar. A jump must truncate the history to that step. It must not leave later entries in place.
You have three options for stale data.
- Keep it and ignore it. Compute the active path from the data and read only the fields that belong to steps on that path. The old company name stays in memory, so if the user flips back to "business" it reappears. This is friendly, but you must be disciplined about reading only the active fields.
- Delete it when the branch changes. When
advanceleaves a step whose answers changed, remove the fields that belonged to the abandoned steps. This is simple to reason about but loses user input. - Keep it, but filter at submission. Walk the active path and build the payload from those steps only.
Option 3 is the usual choice. To support it, each step must say which fields it owns. A small helper can compute the active path by replaying next from the first step:
function activePath(
startId: string,
data: Data,
steps: Record<string, Step>
): string[] {
const path: string[] = [];
let id: string | null = startId;
const seen = new Set<string>();
while (id !== null) {
if (seen.has(id)) throw new Error("Cycle in flow at step " + id);
seen.add(id);
path.push(id);
id = steps[id].next(data);
}
return path;
}
console.log(activePath("account", { email: "[email protected]", accountType: "personal" }, steps));
console.log(
activePath("account", { email: "[email protected]", accountType: "business", company: "Acme" }, steps)
);The first call prints [ 'account', 'review' ]. The second prints [ 'account', 'company', 'review' ]. The seen set guards against a cycle. A cycle is a next function that sends the user back to a step already visited. Without the guard, a mistake in one rule would hang the program in an infinite loop.
Branching and validation together
Validation runs on the current step only. That keeps errors local, but branching creates a gap: an answer on an earlier step can make a later step's data required or irrelevant. Two rules close the gap.
- Validate a step only when it is on the active path. A skipped step must not block submission. If the final check validates every step in the table, a personal user fails with "Enter your company name." on a step they never saw.
- Validate again at submission, across the whole active path. A user who edits an earlier answer from the review screen may have changed which later steps apply. The per-step check at the time of entry no longer covers that case.
function validatePath(data: Data, steps: Record<string, Step>): Record<string, string[]> {
const result: Record<string, string[]> = {};
for (const id of activePath("account", data, steps)) {
const errors = steps[id].validate(data);
if (errors.length > 0) result[id] = errors;
}
return result;
}The return value maps step ids to error lists. The review screen can use it to link each message to the step that needs fixing. A step that reports errors after the user has already passed it is the signal to send them back there.
Choosing what a branch depends on
Not every answer should drive a branch. Branches add paths, and every path costs design, testing, and progress-display work. Use these criteria.
| Question | Branch? |
|---|---|
| Does the answer make whole questions irrelevant? | Yes. Skip them. |
| Does it only change one optional field? | No. Show or hide the field on the same step. |
| Does it change which rules apply to a later step? | Usually no. Pass the answer into that step's `validate`. |
| Does the answer change legal or business requirements, such as extra documents? | Yes. Make a separate step. |
A branch that merely hides one field on the same screen does not need a new step. Reserve step-level branching for cases where entire screens become irrelevant or new ones are required.
Also limit how many answers feed one next function. If a decision depends on four earlier answers, it is hard to explain to the user why they see a given step. Prefer a derived value, such as needsTaxInfo, computed in one place and named for its meaning.
Branching and progress display
Branches change the number of remaining steps. A progress bar that says "2 of 3" is false for a user whose path later grows to four steps. The robust choice is to show the position without a fixed total:
function progressLabel(state: FlowState): string {
return "Step " + (state.history.length + 1);
}The label uses the history length, so it stays correct after Back and after a branch. The next chapter covers progress indicators in more detail. For now, note the rule: do not display a total that a later answer can change.
Common mistakes
- Recomputing Back from data instead of using the history stack.
- Submitting the whole data object, including answers from abandoned branches.
- Validating skipped steps at final submission.
- Having a default case missing in
next, which sends users toundefinedwhen an answer is empty. - Allowing a jump to an earlier step without truncating the history.
- Letting
nextdepend on something other thandata, which makes paths impossible to reproduce in a test.
Exercise
A user chooses "business", enters the company name "Acme", reaches review, then goes Back to the account step and changes the type to "personal". They advance to review again and submit. Using the code in this chapter, which step ids does activePath return, and what should the submitted payload contain regarding the company field?
Show answer
activePath returns ["account", "review"], because account.next now returns "review" for a personal account. The company step is not on the active path, so the payload must not include the company field, even though "Acme" is still stored in data. Building the payload from the active path's steps, and not from the whole data object, is what removes it.
Exercise
Add a third account type, "nonprofit", that goes to a new step registration (asking for a registration number) before review. Which parts of the code must change, and which can stay the same?
Show answer
Add a registration entry to the step table with its own validate and a next that returns "review". Change account.next so that "nonprofit" returns "registration". If you use the StepId union, add "registration" to it. advance, back, activePath, and validatePath stay the same, because they only follow what each step's next returns.