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

State Updates Based on State Without Functional Form

How setState(state + 1) in an effect with state as dependency causes loops; use functional updates instead.

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:

  1. Effect runs, reads count (say, 0)
  2. Calls setCount(0 + 1), setting count to 1
  3. Count changed → effect dependencies changed
  4. Effect runs again, reads new count (1)
  5. Calls setCount(1 + 1), setting count to 2
  6. 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.