When Computation Happens: Render vs Effect Timing
What you'll learn: Why running expensive computations in effects causes double slowdowns, and how running them during render is faster.
The Timing Problem
Remember that effects run after the render completes. This creates a two-phase slowdown:
- Render phase: React builds the component tree (potentially slow if you have complex JSX)
- Effect phase: Your effect runs (potentially slow if you're doing heavy computation)
If you put expensive computation in an effect, the user sees the old UI during the slow render, then waits again during the slow effect, then sees a re-render with the new value. That's two delays instead of one.
The Better Pattern
Compute during render instead. React is designed to handle this:
- The computation happens while React is already working
- The correct value appears in the first paint
- No second render needed
- Users see the loading state once, not twice
Think of It Like Cooking
Imagine you're making a sandwich:
- Effect timing: Make the bread, serve it, then go back to the kitchen to add toppings, serve again
- Render timing: Prepare everything together, serve the complete sandwich once
The second approach is always faster and smoother.
When This Matters
Anytime you're filtering arrays, calculating totals, transforming data, or deriving values from props or state — do it during render. Effects are for synchronizing with external systems, not for transforming your own data.
Key Takeaway: Expensive computations belong in the render phase (with useMemo if needed), not in effects. Effects delay results and cause extra renders. Compute during render to show correct values immediately.