Course contentsShow
← React
Lesson 629 of 2,39617. Common useEffect MistakesFree lesson

The Empty Dependency Array Escape Hatch Gone Wrong

Understanding when omitting dependencies seems to fix loops but creates stale closure bugs instead.

The Empty Dependency Array Escape Hatch Gone Wrong

What you'll learn: Why using an empty dependency array to "fix" an infinite loop creates silent bugs with stale data instead.

The Tempting "Fix"

You've got an infinite loop in your effect. The ESLint warning is screaming at you. You discover that adding an empty array [] makes everything stop re-running. Problem solved, right?

Wrong. You've just traded a loud, obvious bug for a quiet, insidious one.

What Actually Happens

When you use [], your effect runs once on mount and captures the props, state, and functions from that first render. Forever. Even when those values change later, your effect still references the old, stale versions—it's trapped in a closure from the past.

function BrokenCounter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const timer = setInterval(() => {
      console.log(count); // Always logs 0!
      setCount(count + 1); // Always sets to 1!
    }, 1000);
    return () => clearInterval(timer);
  }, []); // Empty array = stale closure trap

  return <div>{count}</div>;
}

The count inside the effect is frozen at 0. The timer always increments from zero to one, over and over.

The Right Approach

Either include the dependency (and fix the loop properly with functional updates or memoization), or remove the need for it entirely:

setInterval(() => {
  setCount(c => c + 1); // Functional form doesn't need count in closure
}, 1000);

Now you can safely use [] because you're not relying on stale values.

Key Takeaway: An empty dependency array isn't a magic fix for loops—it just hides the problem by freezing your effect in time. Always question why you need it empty, and fix the underlying issue instead.