Finite State Machines for UI vs Stale Closures in Hooks & Callbacks
Pure (state, event) => nextState reducers evaluate transitions cleanly without closing over stale flags.
Structured Comparison Matrix
| Dimension | Finite State Machines for UI | Stale Closures in Hooks & Callbacks |
|---|---|---|
| Mental Model | Replaces overlapping boolean flags (isLoading, isError, isRetrying) with a discriminated union and explicit (state, event) transition table that makes invalid states unrepresentable. | Explains how JavaScript lexical closures snapshot primitive state per render, causing timers, listeners, and suppressed dependency arrays to read outdated values. |
| Maturity & Domain | Baseline · Widely · State & Architecture Chrome 1+ (Pure JS / Switch-Case) · Firefox 1+ (Pure JS / Switch-Case) · Safari 1+ (Pure JS / Switch-Case) | Baseline · Widely · State & Architecture Chrome 1+ (ECMAScript Lexical Scoping) · Firefox 1+ (ECMAScript Lexical Scoping) · Safari 1+ (ECMAScript Lexical Scoping) |
| Prerequisites | Foundational primitive | |
| When Not to Use | When not to use an FSM: For continuous numeric values (scroll offset, canvas coordinates) or simple independent form fields, plain state or reactive signals are far lighter. | When not to use useRef to bypass dependencies: Don't stuff reactive UI state into a ref just to silence a linter, if the effect should re-run when userId changes, keep userId in the dependency array, or move filter/navigation state to URL as State Store. |
Engine Mechanics & Trade-Offs
Replaces N overlapping boolean flags (2^N states) with a discriminated union of valid states and an explicit (state, event) -> nextState transition table.
Key Pitfalls: Event explosion on simple toggles: Writing a 60-line statechart configuration for an open/closed disclosure panel adds ceremony with zero safety gain. Forgetting cleanup on state exit: Cancelling an in-flight AbortController when leaving loading -> idle must happen deterministically on transition, or stale responses st
Captures immutable primitive values inside a render's lexical closure; async callbacks or omitted dependency arrays read outdated snapshots unless bridged via refs or functional updaters.
Key Pitfalls: Silencing react-hooks/exhaustive-deps: Adding // eslint-disable-next-line to force an effect to run once is the fastest way to ship stale auth tokens or outdated filters in WebSocket handlers. Debounced callbacks capturing old props: Creating a debounced save() inside render without memoizing or reading a ref sends yes
Seen in Architecture Autopsies
Rapid double-click or 3G network blip charges the user twice despite a disabled={isSubmitting} React button.
SPA operations dashboard climbs from 120 MB to 2.4 GB RAM over an 8-hour shift and crashes with Aw, Snap!
Changing a single URL filter triggers an infinite render loop, Maximum update depth exceeded, and a burst of 429 Too Many Requests responses.