Stale Closures

Click twice, and two timers add one each. Why does the count only reach 1? Each timer remembers the count from its own render.

React · intermediate · 8 min · 14 steps · free

What you'll learn

StaleClosure.jsx

import { useState } from 'react';

export default function DelayedCounter() {
  const [count, setCount] = useState(0);

  function addLater() {
    setTimeout(() => {
      setCount(count + 1);
    }, 1000);
  }

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={addLater}>+1 in a second</button>
    </div>
  );
}

Step by step

  1. React renders <DelayedCounter> for the first time: it calls the DelayedCounter function.
  2. useState runs for the first time, so React stores the starting value for count and returns it: 0.
  3. DelayedCounter returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.
  4. React turns the JSX into real page elements and shows them: look at the Screen panel.
  5. You click the “+1 in a second” button. React calls its onClick handler.
  6. addLater schedules a function to run in one second. That function can see count from this render: 0.
  7. You click again before the first timer fires. No render happened in between, so this click also sees count = 0.
  8. Runs setTimeout(() => { setCount(count + 1); }, 1000);.
  9. A second later the first timer fires: setCount(count + 1) with count = 0 from render 1, so it queues "set to 1".
  10. The second timer also sees count = 0, so it queues "set to 1" again.
  11. React renders <DelayedCounter> again (render 2): it calls DelayedCounter once more, from the top.
  12. useState returns the value React has kept for count: 1. The starting value is only used on the first render.
  13. DelayedCounter returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.
  14. Count: 1, not 2. Try the fixed version, which uses an update function.

Common mistakes

Best practices

Key takeaways

Check yourself

A timer made in render 1 reads count. It gets?

Answer: Render 1's count

The fix for delayed updates?

Answer: setCount(c => c + 1)

·

More in How Rendering Works