The Real Fullstack

The Stale Closure

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

Explorador6 minDesafio de códigoLaboratório de depuração
reactjavascripthooks

Este desafio ainda não foi traduzido para Português (Brasil). Você está lendo a versão em inglês.

Missão:Predict what the counter shows, explain why, and fix both the counter and the timer that never stops.Contexto · Objetivos de aprendizagem ▾

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.

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

Objetivos de aprendizagem

  • 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.
SimulaçãoSimulado

Execute a simulação para ver a saída.

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

Simplificação

Two symptoms with deterministic fixes. The same capture problem appears with event listeners, sockets and async callbacks. Modelo educacional — os números ilustram comportamento, não são benchmarks.

Conceitos

Desafios relacionados

Referências