State Updates Based on State Without Functional Form
What you'll learn: Why using setState(state + 1) inside a useEffect with state as a dependency creates infinite loops, and how functional updates solve this.
The Problem
When you read the current state and use it to calculate the next state inside a useEffect, you create a dangerous pattern:
const [count, setCount] = useState(0);
useEffect(() => {
setCount(count + 1); // ❌ Creates infinite loop!
}, [count]);
Here's what happens:
- Effect runs, reads
count(say, 0) - Calls
setCount(0 + 1), setting count to 1 - Count changed → effect dependencies changed
- Effect runs again, reads new
count(1) - Calls
setCount(1 + 1), setting count to 2 - Loop repeats forever!
The Solution: Functional Updates
Use the functional form of setState, which receives the current state as an argument:
const [count, setCount] = useState(0);
useEffect(() => {
setCount(c => c + 1); // ✅ No loop!
}, []); // Empty array — runs once
Now you don't need count in the dependency array because you're not reading it directly. React passes the current value to your updater function automatically.
When This Matters
This pattern is crucial when:
- Incrementing counters based on intervals
- Accumulating values over time
- Any state update that depends on the previous value
Key Takeaway: Never use setState(state + something) inside a useEffect that depends on state — use setState(prev => prev + something) and remove state from dependencies to avoid infinite loops.