# Stale Closures in Hooks & Callbacks vs URL as a State Store

- **Canonical URL:** https://frontend.rocks/vs/stale-closures-hooks-vs-url-as-state-store/
- **Relation:** Contrasts With
- **Last Verified:** 2026-11-15
- **Verdict:** Hook closures snapshot per-render filter state, whereas URL search params act as a single external source of truth.

## Comparison Matrix

| Dimension | Stale Closures in Hooks & Callbacks | URL as a State Store |
| :--- | :--- | :--- |
| **Maturity** | Baseline · Widely | Baseline · Widely |
| **Domain** | State & Architecture | State & Architecture |
| **Mental Model** | Explains how JavaScript lexical closures snapshot primitive state per render, causing timers, listeners, and suppressed dependency arrays to read outdated values. | Persists shareable, reload-safe view state (filters, tabs, pagination) in URLSearchParams—using pushState for discrete steps and replaceState for continuous edits. |
| **Prerequisites** | Virtual DOM & Reconciliation (Each VDOM re-render invokes the component function anew, creating fresh lexical scopes.) | None |
| **When Not to Use** | 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. | When not to use the URL as a state store: Never put sensitive tokens, PII, ephemeral hover/drag coordinates, or multi-kilobyte payloads in the URL (browsers and proxies cap URL lengths around 2–8 KB). |

## 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);
}, []);
```

## URL as a State Store — Under the Hood
The browser's session history stack is an ordered list of `(URL, state)` tuples that survives reloads and integrates with [bfcache](/concepts/bfcache-navigation). Treating the URL as a state store means avoiding [Stale Closures](/concepts/stale-closures-hooks) by deriving UI directly from the parsed location rather than mirroring it into duplicate component state.

1. Parse `new URLSearchParams(window.location.search)` through a strict validator that coerces types and falls back to safe defaults on malformed query strings.
2. Call `history.pushState()` for discrete, Back-navigable transitions (switching tabs, advancing page 1 -> page 2).
3. Call `history.replaceState()` for continuous or noisy edits (search-as-you-type, map pan coordinates) so the user's Back button still exits cleanly.

```js
function updateSearchParam(key, value, { replace = false } = {}) {
  const url = new URL(window.location.href);
  value ? url.searchParams.set(key, value) : url.searchParams.delete(key);
  const method = replace ? 'replaceState' : 'pushState';
  window.history[method](null, '', url);
}
```

## Interactive Labs & Dissections
- [Stale Closures in Hooks & Callbacks Lab](https://frontend.rocks/concepts/stale-closures-hooks/#lab) ([Markdown](https://frontend.rocks/concepts/stale-closures-hooks.md))
- [URL as a State Store Lab](https://frontend.rocks/concepts/url-as-state-store/#lab) ([Markdown](https://frontend.rocks/concepts/url-as-state-store.md))

## Related Architecture Autopsies
- [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 #06: Anatomy of a Hydration Mismatch & Full Subtree Bailout](https://frontend.rocks/autopsies/hydration-flicker-and-bailout/) ([Markdown](https://frontend.rocks/autopsies/hydration-flicker-and-bailout.md)): SSR page paints instantly, flickers violently when JS boots, and wipes user input in form fields.
- [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://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
- https://react.dev/reference/react/useEffect
- https://react.dev/learn/separating-events-from-effects
- https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
- https://developer.mozilla.org/en-US/docs/Web/API/History_API
- https://developer.mozilla.org/en-US/docs/Web/API/Navigation_API
