Skip to content

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

### Why are refs stable across renders??

React guarantees useRef returns the same reference across all renders. Only .current property changes. Thats why refs not needed in deps.

What if I need to react to ref.current change??

Refs are intentionally not reactive. Use state instead if you need to react to changes. Refs are for mutable values that should not cause re-renders.

Can I use ref to store previous value??

Yes common pattern: const prevRef = useRef(); useEffect(() => { prevRef.current = value; }, [value]);

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