0 day streak
javascript / intermediate
Snippet

Conditional Multi-Step Rendering Using Switch Statements on Discriminated State

Using a `switch` statement over a discriminated status string allows clear, deterministic flow control in multi-step React workflows. Including a default case with exhaustive failure handling guarantees that unsupported status transitions throw identifiable errors during development.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function RegistrationFlow({ onComplete }) {
const [stepState, setStepState] = React.useState({ stage: 'EMAIL', data: {} });
const advance = (nextStage, payload) => {
setStepState((prev) => ({ stage: nextStage, data: { ...prev.data, ...payload } }));
};
const renderStage = () => {
switch (stepState.stage) {
case 'EMAIL':
return <button onClick={() => advance('PASSWORD', { email: '[email protected]' })}>Submit Email</button>;
case 'PASSWORD':
return <button onClick={() => advance('CONFIRM', { pass: 'secret' })}>Set Password</button>;
case 'CONFIRM':
return <button onClick={() => onComplete(stepState.data)}>Finalize</button>;
default: {
const exhaustiveCheck = stepState.stage;
throw new Error(`Unhandled wizard stage: ${exhaustiveCheck}`);
}
}
};
return <main className="wizard-container">{renderStage()}</main>;
}
react
Breakdown
1
switch (stepState.stage) {
Evaluates the explicit stage property to determine which step UI component to display.
2
case 'EMAIL':
Branches execution to render the initial input stage while maintaining access to state transitions.
3
const exhaustiveCheck = stepState.stage;
Ensures any unhandled or malformed state variant triggers an immediate diagnostic exception.