Build a Three-Stage Signup Wizard with React Reducer State
Data Structure DesignModel answerLast updated
Design a React wizard with profile, address and review stages, covering validation, guarded navigation, disabled controls, a submit spinner and server error display, plus scaling and performance trade-offs.
Build a React component that implements a three-stage wizard for collecting a user's details.
Stages
- Profile: the user's basic personal information (for example name and email).
- Address: street, city and postal code.
- Review: a read-only summary of everything entered, with a button to confirm and send.
Functional requirements
- Each field has simple validation (required values, a plausible email format, a postal code pattern).
- The user can move forward, move back, and jump between stages using a step indicator.
- Controls must be enabled or disabled sensibly. For example, the user must not be able to skip past invalid stages or trigger a second submission while one is in flight.
- While the final submission is pending, show a loading state.
- If the submission fails, show a clear error message and let the user retry without losing their data.
Expected deliverable
Write the component (the submit handler is passed in as an async prop that may reject). Be prepared to discuss:
- Why you would manage the wizard with a reducer rather than several independent
useStatehooks. - How you would structure the code as the number of stages grows large.
- How to design error messages so they are friendly to users yet simple to reason about in code.
- Which performance optimizations are worth applying (memoization, lazy rendering, and so on).
Hints
Hint 1
Model the wizard as a small state machine: current step, all field values, which fields were touched, a submit status (idle, submitting, error, success) and the server error message, all in one reducer.
Hint 2
Describe the stages with a config array (title and field list) and keep validation a pure function of the values. Derive disabled flags, visible errors and the spinner from state instead of storing them separately.
Hint 3
Put navigation guards in the reducer: Next only advances if the current stage validates, jumping to stage k requires every earlier stage to be valid, and a submit action is ignored while already submitting. Show a field's error only after it has been touched.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat the wizard as a state machine whose whole state lives in one reducer. The UI is a projection of that state.
State shape:
step: index of the current stage.values: every field across all stages.touched: which fields the user has interacted with.status:idle | submitting | error | success.submitError: message from a failed submission, ornull.
Stages come from a config array such as { title, fields: Field[] }. Validators are pure functions (value) => string | undefined, so the errors for a stage are just validate(values, STEPS[step].fields). Nothing about errors, disabled flags or the spinner is stored separately; it is all derived.
Why this is correct
- No impossible states.
submitclears the previous error and setsstatus = "submitting"in one transition.failuresets bothstatus = "error"and the message together. With severaluseStatecalls these updates can drift apart (for example a spinner and a stale error visible together). - Guards live in one place.
nextmarks the current stage's fields as touched and advances only if they are valid.goto(k)is allowed only if all fields in stages beforekare valid. This stays true even if the user goes back and breaks an earlier field.backandgotoare ignored while submitting.
- No double submit. The button is disabled while
busy, the reducer ignoressubmitwhen already submitting, and auseRefflag blocks a second click that lands before React re-renders. - Errors appear at the right moment. Show a field's error only if it is touched (on blur or after a failed Next). Users are not scolded while typing the first character.
- Retry keeps data. A failure only changes
statusandsubmitError;valuesis untouched. Editing any field clears the error and returns toidle.
Sketch of the code
type Status = "idle" | "submitting" | "error" | "success";
function reducer(s: State, a: Action): State {
const busy = s.status === "submitting";
switch (a.type) {
case "change":
return { ...s, values: { ...s.values, [a.field]: a.value },
status: s.status === "error" ? "idle" : s.status, submitError: null };
case "blur":
return { ...s, touched: { ...s.touched, [a.field]: true } };
case "next": {
const fields = STEPS[s.step].fields;
const touched = { ...s.touched };
fields.forEach(f => (touched[f] = true));
if (!isValid(s.values, fields)) return { ...s, touched };
return { ...s, touched, step: Math.min(s.step + 1, STEPS.length - 1) };
}
case "back":
return busy ? s : { ...s, step: Math.max(0, s.step - 1) };
case "goto":
if (busy || a.step < 0 || a.step >= STEPS.length) return s;
return isValid(s.values, fieldsBefore(a.step)) ? { ...s, step: a.step } : s;
case "submit":
return busy ? s : { ...s, status: "submitting", submitError: null };
case "success":
return { ...s, status: "success" };
case "failure":
return { ...s, status: "error", submitError: a.error };
}
}
The component wires it up:
const handleSubmit = async () => {
if (inFlight.current) return;
inFlight.current = true;
dispatch({ type: "submit" });
try {
await onSubmit(values);
dispatch({ type: "success" });
} catch (e) {
dispatch({ type: "failure",
error: e instanceof Error && e.message ? e.message : "Submission failed. Please try again." });
} finally {
inFlight.current = false;
}
};
Render the current stage's fields from config, a read-only list on the review stage, the error banner when submitError is set, a Back button disabled on the first stage or when busy, and a primary button labeled "Next", "Submit" or "Submitting…" that is disabled while busy.
Discussion points
Reducer vs. multiple useState. The stage index, values, touched flags, status and error are interdependent. A reducer makes each user event one atomic, testable transition (pure function, easy unit tests, no stale closures), and the guards sit beside the data they protect. Separate hooks scatter these rules across handlers and allow inconsistent intermediate states. For a very small form useState is fine; the reducer pays off once transitions have rules.
Scaling to many stages. Keep stages declarative: each has a config entry (fields, validators, optional conditional visibility) and, if needed, its own small component. Generic navigation and validation code iterates the config. Group validators per stage, and consider a schema library (Zod, Yup) for shared client and server rules. For branching flows, compute the list of active stages from values. Consider a context provider if deeply nested components need dispatch.
Error message design.
- Field errors: short, specific and actionable ("Enter a 5-digit ZIP code"), shown after touch or Next attempt, linked to the input with
aria-describedbyand announced withrole="alert". - Submission errors: one banner near the action, with the server's message when safe, otherwise a generic fallback and a retry path.
- In code, keep validators returning plain strings or codes so the logic stays separate from presentation; map codes to copy (and translations) in one place.
Performance.
- Wrap field components in
React.memoand pass a stabledispatch, so typing in one field does not rerender the others. - Memoize stage validation with
useMemokeyed onvaluesandstep. - Render only the current stage (lazy rendering); code-split heavy stages with
React.lazy. - For large forms, debounce expensive validation (such as async uniqueness checks) and avoid putting values in a context that every field subscribes to.
- Measure first; for three stages most of this is optional.
Common mistakes
- Storing
isLoading,hasErroranderrorsas separate state that falls out of sync. - Validating only the current stage, so users can jump ahead past invalid stages.
- Disabling Submit but not guarding the handler, allowing a double click.
- Clearing form values on failure.
- Showing errors on pristine fields immediately.
- Forgetting accessibility: labels, error association and focus management on step change.
Complexity
Each action is O(number of fields in the validated stages), which is tiny. Rendering cost is bounded by the current stage's fields when memoization and per-stage rendering are used.