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

The Classic Infinite Loop: setState in Effect Body

Understanding why calling setState unconditionally inside useEffect creates an infinite render loop.

The Classic Infinite Loop: setState in Effect Body

You'll learn why unconditionally calling setState inside useEffect creates an infinite render loop—and how to recognize this mistake instantly.


The Problem

When you call setState inside useEffect without conditions or proper dependencies, you create a feedback loop:

  1. Component renders
  2. Effect runs after render
  3. Effect calls setState
  4. State change triggers re-render
  5. Effect runs again (because state changed)
  6. Back to step 3 → infinite loop

The Code That Breaks Everything

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

  useEffect(() => {
    setCount(count + 1); // 🔥 INFINITE LOOP!
  }, [count]); // Runs whenever count changes

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

Every render increments count, which triggers the effect, which increments count again... forever. Your browser tab freezes, React warns you, chaos ensues.

The Analogy

Imagine a thermostat that always adjusts the temperature after measuring it, then immediately measures again and adjusts again. It never stops "correcting" itself.

How to Fix It

Option 1: Add a condition inside the effect:

useEffect(() => {
  if (count < 10) {
    setCount(count + 1);
  }
}, [count]);

Option 2: Use an empty dependency array if you only want it once:

useEffect(() => {
  setCount(5);
}, []); // Only runs on mount

Key Takeaway: Calling setState unconditionally inside useEffect when that state is also a dependency creates an infinite loop. Always add conditions or rethink whether the effect pattern fits your use case.