javascript / intermediate
Snippet
Exhaustive Switch-Case Control Flow for Reducer State Transitions
A switch statement controls branch execution based on action identifiers inside state reducer functions. Using explicit case branching alongside an unhandled default branch that throws an error guarantees deterministic state mutations and catches invalid action types immediately 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
25
26
27
28
29
import React, { useReducer } from 'react';const initialState = { count: 0 };function counterReducer(state, action) {switch (action.type) {case 'increment':return { ...state, count: state.count + action.payload };case 'decrement':return { ...state, count: Math.max(0, state.count - action.payload) };case 'reset':return initialState;default:throw new Error(`Unhandled action type: ${action.type}`);}}export function CounterWidget() {const [state, dispatch] = useReducer(counterReducer, initialState);return (<div><p>Count: {state.count}</p><button onClick={() => dispatch({ type: 'increment', payload: 1 })}>+1</button><button onClick={() => dispatch({ type: 'decrement', payload: 1 })}>-1</button><button onClick={() => dispatch({ type: 'reset' })}>Reset</button></div>);}
react
Breakdown
1
switch (action.type) {
Evaluates the action descriptor string to determine which control flow branch to execute.
2
case 'increment':
Matches the specific action type to return a new object with updated numerical state.
3
default:
Catches any unhandled action types that do not match expected case clauses.
4
throw new Error(`Unhandled action type: ${action.type}`);
Fails fast at runtime if an invalid or misspelled action type is dispatched.