How to Fix useEffect with Ref Dependencies
DodaTech
Updated 2026-06-26
1 min read
The Problem
In this quick-fix, you'll learn how to use refs in effects without including them in deps. This matters because including refs in deps causes unnecessary effect re-runs. In real-world applications, this pattern appears in storing mutable values interval IDs DOM refs.
The Wrong Way
function Timer() {
const [count, setCount] = useState(0);
const intervalRef = useRef(null);
useEffect(() => {
intervalRef.current = setInterval(() => setCount(c=>c+1), 1000);
return () => clearInterval(intervalRef.current);
}, [intervalRef]); // Ref included -- unnecessary
return <div>{count}s</div>;
}
Works but ref dependency is unnecessary -- ref identity is stable
The Right Way
function Timer() {
const [count, setCount] = useState(0);
const intervalRef = useRef(null);
useEffect(() => {
intervalRef.current = setInterval(() => setCount(c=>c+1), 1000);
return () => clearInterval(intervalRef.current);
}, []);
return <div>{count}s</div>;
}
Cleaner -- ref intentionally omitted ref is stable across renders
Prevention
- Refs have stable identity not needed in deps
- Use refs for values persisting across renders without causing re-renders
- Access ref.current in effects without including ref in deps
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 Observable Subscription Leaks
Next →
How to Fix useEffect Running Multiple Times
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro