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
This guide is brought to you by DodaTech -- built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
← Previous
How to Fix Event Listener Memory Leaks
Next →
How to Fix useEffect Mount Logic Dependencies
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro