Skip to content

How to Fix useEffect Interval Timer Issues

DodaTech Updated 2026-06-26 1 min read

The Problem

In this quick-fix, you'll learn how to correctly implement setInterval with proper cleanup. This matters because interval timers are common source of memory leaks. In real-world applications, this pattern appears in countdown timers live clocks polling auto-saving.

The Wrong Way

function LiveClock() {
  const [time, setTime] = useState(new Date());
  useEffect(() => { setInterval(() => setTime(new Date()), 1000); }); // Missing deps and cleanup
  return <div>{time.toLocaleTimeString()}</div>;
}
New interval on every render -- multiple intervals accumulate

The Right Way

function LiveClock() {
  const [time, setTime] = useState(new Date());
  useEffect(() => { const id = setInterval(() => setTime(new Date()), 1000); return () => clearInterval(id); }, []);
  return <div>{time.toLocaleTimeString()}</div>;
}
One interval created on mount cleared on unmount

Prevention

  • Store interval ID and clear in cleanup
  • Use empty deps for one-time interval setup
  • Use refs for interval IDs accessed outside effect

FAQ

### Why does my interval run faster than expected??

Missing deps causes effect and setInterval to run every render. Multiple intervals accumulate. Always provide deps and clean up previous intervals.

How to update interval dynamically??

Include duration in deps: useEffect(() => { const id = setInterval(tick, duration); return () => clearInterval(id); }, [duration]);

Can I use setTimeout instead of setInterval??

Yes for one-time delays. setInterval more efficient for recurring. Recursive setTimeout for variable-interval timing.

This guide is brought to you by DodaTech -- built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro