The Stale State Problem with useEffect
You'll learn why using useEffect to update derived state creates values that are always one render behind and can cause unpredictable bugs.
The One-Render-Behind Bug
When you use useEffect to compute derived state, there's a fundamental timing problem: the effect runs after the render completes. This means your derived state is always showing the previous value, not the current one.
Here's what happens:
- Render 1: Props change → Component renders with old derived state → Effect runs → Updates derived state
- Render 2: Component re-renders with the now-updated derived state from the previous render
Your UI is always showing yesterday's calculation.
The Race Condition Problem
Even worse, rapid changes create race conditions. Imagine props changing from A → B → C quickly:
- Effect for A starts computing
- Props change to B, effect for B starts
- Effect for C starts
- Effect A finishes, sets state (wrong!)
- Effect B finishes, sets state (also wrong!)
- Effect C finishes, sets state (finally correct)
Your component flickers through incorrect values before settling. Users see wrong data briefly—or not so briefly if the calculation is slow.
Why This Happens
useEffect is designed for synchronization with external systems, not for transforming data. When you use it for derived state, you're fighting React's rendering model. The effect cleanup and scheduling system can't guarantee order when multiple updates happen quickly.
Key Takeaway: Using useEffect to compute derived state guarantees stale values (one render behind) and opens the door to race conditions where the wrong calculation wins—always compute derived values directly during render instead.