Course contentsShow
← React
Lesson 373 of 2,39611. useState Patterns and PitfallsFree lesson

Functional Updates in useEffect

Why setCount(c => c + 1) in effects removes the need to include count in the dependency array.

Why setCount(c => c + 1) in Effects Removes the Need to Include count in the Dependency Array

You'll learn: How functional updates let your effects read and update state without listing that state in the dependency array, preventing infinite loops and stale closures.


The Problem with Direct State Reads in Effects

When you use count directly inside a useEffect like setCount(count + 1), React's linter demands you add count to the dependency array. But if your effect sets count, it triggers a re-render, which runs the effect again… infinite loop!

useEffect(() => {
  const timer = setInterval(() => {
    setCount(count + 1); // Uses count from closure
  }, 1000);
  return () => clearInterval(timer);
}, []); // Missing 'count' — always uses initial value!

This effect has a stale closure: count is trapped at its initial value forever.


The Solution: Functional Updates

Use the updater function syntax — setCount(c => c + 1) — which reads the current state directly from React, not from your closure:

useEffect(() => {
  const timer = setInterval(() => {
    setCount(c => c + 1); // React provides latest c
  }, 1000);
  return () => clearInterval(timer);
}, []); // No 'count' needed!

Now the effect depends on nothing — the empty array is safe. The functional update guarantees you always work with the latest state value, even though your effect only runs once.


The Mental Model

Think of c => c + 1 as asking React: "Whatever count is right now, add 1 to it." You're not relying on a stale snapshot from when the effect was created.


Key Takeaway: Functional updates (setState(prev => ...)) in effects let you update state without including it in dependencies, avoiding infinite loops and stale closures while keeping your dependency array honest.