# Finite State Machines for UI vs Stale Closures in Hooks & Callbacks

- **Canonical URL:** https://frontend.rocks/vs/finite-state-machines-ui-vs-stale-closures-hooks/
- **Relation:** Contrasts With
- **Last Verified:** 2026-11-15
- **Verdict:** Pure (state, event) => nextState reducers evaluate transitions cleanly without closing over stale flags.

## Comparison Matrix

| Dimension | Finite State Machines for UI | Stale Closures in Hooks & Callbacks |
| :--- | :--- | :--- |
| **Maturity** | Baseline · Widely | Baseline · Widely |
| **Domain** | State & Architecture | State & Architecture |
| **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. |
| **Prerequisites** | None | Virtual DOM & Reconciliation (Each VDOM re-render invokes the component function anew, creating fresh lexical scopes.) |
| **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. |

## Finite State Machines for UI — Under the Hood
Boolean flags act like four light switches wired to one bulb: nothing stops code from flipping `isLoading` and `isError` on together. A Finite State Machine works like a rotary dial, only one position is active, blocking [Optimistic UI](/concepts/optimistic-ui-rollback) races and [Stale Closures](/concepts/stale-closures-hooks).

1. **Finite states**: Enumerate every legal mode (`idle | loading | success | error`) as a tagged union.
2. **Events**: Represent triggers as explicit objects (`{ type: 'SUBMIT' }`) rather than ad-hoc setter calls.
3. **Transition function**: A pure `transition(state, event)` checks the current state first, ignoring any event not valid for that state.

```ts
type State = { status: 'idle' } | { status: 'loading' } | { status: 'error'; message: string };
type Event = { type: 'FETCH' } | { type: 'FAIL'; message: string } | { type: 'RESET' };

function transition(state: State, event: Event): State {
  if (state.status === 'idle' && event.type === 'FETCH') return { status: 'loading' };
  if (state.status === 'loading' && event.type === 'FAIL') return { status: 'error', message: event.message };
  if (state.status === 'error' && event.type === 'RESET') return { status: 'idle' };
  return state; // Invalid event for current state is safely ignored
}
```

## Stale Closures in Hooks & Callbacks — Under the Hood
A stale closure is standard ECMAScript lexical scoping colliding with [Virtual DOM](/concepts/virtual-dom-reconciliation) re-renders and [Event Loop](/concepts/event-loop-tasks-microtasks) callbacks. Each render prints a dated Polaroid: a timer created in Render #1 carries that Polaroid even after Render #10 hangs a newer photo.

1. Render #1 declares `const count = 0` and passes `() => setCount(count + 1)` to `setInterval`.
2. When the timer fires 1,000 ms later, V8 resolves `count` against Render #1's `LexicalEnvironment` (`0`), writing `1` every single tick.
3. Passing a functional updater `c => c + 1`, reading a mutable `.current` ref, or switching to [Fine-Grained Signals](/concepts/fine-grained-signals) (which pass a live box rather than a frozen primitive) eliminates the snapshot drift.

```js
// Buggy: closes over Render #1's `count`
useEffect(() => {
  const id = setInterval(() => setCount(count + 1), 1000);
  return () => clearInterval(id);
}, []); // eslint-disable-next-line react-hooks/exhaustive-deps

// Fixed: functional updater reads latest state from the queue
useEffect(() => {
  const id = setInterval(() => setCount((c) => c + 1), 1000);
  return () => clearInterval(id);
}, []);
```

## Interactive Labs & Dissections
- [Finite State Machines for UI Lab](https://frontend.rocks/concepts/finite-state-machines-ui/#lab) ([Markdown](https://frontend.rocks/concepts/finite-state-machines-ui.md))
- [Stale Closures in Hooks & Callbacks Lab](https://frontend.rocks/concepts/stale-closures-hooks/#lab) ([Markdown](https://frontend.rocks/concepts/stale-closures-hooks.md))

## Related Architecture Autopsies
- [Autopsy #01: Anatomy of a Double Payment in Production](https://frontend.rocks/autopsies/double-payment-race-condition/) ([Markdown](https://frontend.rocks/autopsies/double-payment-race-condition.md)): Rapid double-click or 3G network blip charges the user twice despite a disabled={isSubmitting} React button.
- [Autopsy #02: Anatomy of a Memory Leak on an 8-Hour Dashboard](https://frontend.rocks/autopsies/eight-hour-spa-memory-leak/) ([Markdown](https://frontend.rocks/autopsies/eight-hour-spa-memory-leak.md)): SPA operations dashboard climbs from 120 MB to 2.4 GB RAM over an 8-hour shift and crashes with Aw, Snap!
- [Autopsy #13: The useEffect Dependency Loop That DDoSed Our Own API](https://frontend.rocks/autopsies/useeffect-dependency-loop-ddos/) ([Markdown](https://frontend.rocks/autopsies/useeffect-dependency-loop-ddos.md)): Changing a single URL filter triggers an infinite render loop, Maximum update depth exceeded, and a burst of 429 Too Many Requests responses.

## Primary Sources
- https://www.w3.org/TR/scxml/
- https://stately.ai/docs/state-machines-and-statecharts
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
- https://react.dev/reference/react/useEffect
- https://react.dev/learn/separating-events-from-effects
