Why It's Wrong: Double Rendering
What you'll learn: How the "derive state in effect" antipattern forces React to render your component twice unnecessarily, hurting performance.
The Two-Render Penalty
When you use useEffect to set state based on props or other state (like filtering a list), you trigger a wasteful two-step render cycle:
- First render: Component renders with stale or initial derived state
- Effect runs: Detects props changed, calculates new value, calls
setState - Second render: Component re-renders with the updated derived state
Your users see the result of the first render briefly before the correct value appears—even if it's just a few milliseconds.
Why This Happens
Effects run after the component paints to the screen. React can't "go back in time" to fix the first render. The state update from your effect schedules a brand new render cycle.
// ❌ Forces double render
useEffect(() => {
setFiltered(items.filter(item => item.active));
}, [items]);
// Render 1: filtered is stale
// Effect runs, updates filtered
// Render 2: filtered is correct
The Performance Cost
Each render means:
- Running your component function again
- Reconciling the virtual DOM
- Potentially updating the real DOM
- Re-running child component logic
Multiply this across many components or frequent prop changes (like search inputs), and you've created unnecessary work for React.
The Analogy
It's like a restaurant server bringing you the wrong dish, realizing the mistake, then bringing the correct one. Why not just check the order before leaving the kitchen?
Key Takeaway: Deriving state in useEffect guarantees a wasted first render with incorrect data, followed by an immediate correction render—bad for performance and user experience.