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:
- Component renders
- Effect runs after render
- Effect calls
setState - State change triggers re-render
- Effect runs again (because state changed)
- 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.