javascript / intermediate
Snippet
Predictable State Transitions with State Machines
A Finite State Machine (FSM) helps manage complex UI logic by defining explicit states and valid transitions. This prevents 'impossible' states (like being in 'success' and 'loading' simultaneously).
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
const stateMachine = {idle: { SUBMIT: 'loading' },loading: { SUCCESS: 'success', FAILURE: 'error' },error: { RETRY: 'loading' },success: {}};function transition(state, action) {return stateMachine[state]?.[action] || state;}let currentState = 'idle';currentState = transition(currentState, 'SUBMIT'); // 'loading'
nextjs
Breakdown
1
stateMachine = { ... }
A configuration object mapping current states and actions to the next state.
2
stateMachine[state]?.[action]
Uses optional chaining to safely check if a transition exists for the given action.