The Real Fullstack

The Stale Closure

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

Explorateur6 minDéfi de codeLaboratoire de débogage
reactjavascripthooks

Ce défi n'est pas encore traduit en Français. Vous lisez la version anglaise.

Mission:Predict what the counter shows, explain why, and fix both the counter and the timer that never stops.Contexte · Objectifs d'apprentissage ▾

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.

Mission: Predict what the counter shows, explain why, and fix both the counter and the timer that never stops.

Objectifs d'apprentissage

  • 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.
SimulationSimulé

Lancez la simulation pour voir la sortie.

Lancer la simulation
useEffect(() => {  const id = setInterval(() => {    setCount((c) => c + 1);         // always uses the latest state  }, 1000);  return () => clearInterval(id);   // stop the timer when the component unmounts}, []);

Simplification

Two symptoms with deterministic fixes. The same capture problem appears with event listeners, sockets and async callbacks. Modèle pédagogique — les chiffres illustrent un comportement, ce ne sont pas des benchmarks.

Concepts

Défis liés

Références