0 day streak
javascript / intermediate
Snippet

Exhaustive Discriminated Union Evaluation in React useReducer

Controlled state transitions in React `useReducer` handlers benefit from switch-case control flow matching discriminated action strings. Including an exhaustive evaluation block in the `default` case ensures that unexpected runtime action shapes throw immediate descriptive runtime errors rather than silently corrupting application state.

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
25
26
27
28
29
30
import { useReducer } from 'react';
const initialState = { status: 'idle', count: 0, error: null };
function counterStateReducer(state, action) {
switch (action.type) {
case 'INCREMENT':
return { ...state, count: state.count + action.payload.step };
case 'RESET':
return initialState;
case 'FAIL':
return { ...state, status: 'error', error: action.payload.message };
default: {
const exhaustiveCheck = action.type;
throw new Error(`Unhandled action type encountered: ${exhaustiveCheck}`);
}
}
}
export function StepperControl() {
const [state, dispatch] = useReducer(counterStateReducer, initialState);
return (
<div>
<span>Count: {state.count}</span>
<button onClick={() => dispatch({ type: 'INCREMENT', payload: { step: 5 } })}>+5</button>
<button onClick={() => dispatch({ type: 'RESET' })}>Reset</button>
</div>
);
}
react
Breakdown
1
switch (action.type) {
Directs control flow according to the discriminated literal string property of the dispatched action.
2
default: {
Fallback branch entered when an unrecognized action type payload bypasses standard branches.
3
throw new Error(`Unhandled action type encountered: ${exhaustiveCheck}`);
Halts execution immediately with an explicit error identifying the unsupported action discriminator.