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. 教学模型——数字用于说明行为,并非基准测试。

概念

相关挑战

参考资料