The Real Fullstack

The Stale Closure

The interval fires every second. Why does the number never pass 1?

エクスプローラー6 分コード課題デバッグラボ
reactjavascripthooks

この課題はまだ日本語に翻訳されていません。英語版を表示しています。

ミッション:Predict what the counter shows, explain why, and fix both the counter and the timer that never stops.背景 · 学習目標 ▾

A small stopwatch component in Fernpost's dashboard uses useEffect and setInterval. It renders 1 after the first second and then never changes. The console also keeps printing “tick” after navigating away.

ミッション: Predict what the counter shows, explain why, and fix both the counter and the timer that never stops.

学習目標

  • Understand that closures capture values from the render that created them.
  • Update state from the previous state with a functional update.
  • Clean up effects that start timers or subscriptions.
シミュレーションシミュレーション値

シミュレーションを実行すると出力が表示されます。

シミュレーションを実行
useEffect(() => {  const id = setInterval(() => {    setCount((c) => c + 1);         // always uses the latest state  }, 1000);  return () => clearInterval(id);   // stop the timer when the component unmounts}, []);

簡略化

Two symptoms with deterministic fixes. The same capture problem appears with event listeners, sockets and async callbacks. 教育用モデルです。数値は挙動を示すためのもので、ベンチマークではありません。

コンセプト

関連する課題

参考資料