Skip to content

How to Fix React Captured Value in Closures

DodaTech Updated 2026-06-24 2 min read

In this fix, you'll learn why React closures capture the value at render time causing stale reads in setTimeout or event handlers, why this matters for real-time chat apps, and how this pattern affects live polling features.

JavaScript closures capture the value of variables at the time the closure is created. In React, each render creates a new closure with the current state value frozen at that render.

The Problem

The following code demonstrates the typical mistake:

function Timer() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    setInterval(() => {
      setCount(count + 1); // count is always 0
    }, 1000);
  }, []);
  return <p>{count}</p>;
}
// count stays at 1 — captured value is always 0 from the first render

The Fix

Here is the corrected version:

function Timer() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    const id = setInterval(() => {
      setCount(c => c + 1); // functional updater
    }, 1000);
    return () => clearInterval(id);
  }, []);
  return <p>{count}</p>;
}
// count increments by 1 every second correctly

Prevention

  • Always use functional updates (prev => prev + 1) when reading previous state inside closures.
  • Add all dependencies to useEffect/useCallback dependency arrays to recreate the closure.
  • Use useRef to store the latest callback without causing re-renders.
  • For real-time data, use libraries like React Query that manage staleness externally.
  • Consider using useEvent (React 19) for stable callback identity.

Common Mistakes with capture value

  1. Non-exhaustive pattern matches that compile with warnings then crash at runtime
  2. Misunderstanding that String is [Char] with poor performance for large text operations
  3. Using foldl instead of foldl' causing stack overflow on large lists

These mistakes appear frequently in real-world REACT code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### Why does JavaScript capture the old value in closures?

Each render creates a new closure with state frozen at render time. The interval callback captures the count variable from the first render. Since the dependency array is empty [], the effect (and its interval) never re-runs, so it always sees count = 0.

Does useRef solve the captured value problem?

Yes — useRef returns the same object across renders. Mutations to ref.current are visible everywhere. Use it for callbacks that need the latest state without re-registering the effect: ref.current = count.

How does React Query avoid stale data?

React Query manages an external cache (the QueryClient) outside the component lifecycle. Components subscribe to cache changes rather than capturing values in closures. Background refetching keeps data fresh without closure issues.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro