Why Side Effects Can't Run During Render
You'll learn: Why executing side effects during the render phase violates React's architecture and leads to unpredictable bugs.
React's rendering model is built on a fundamental principle: render functions must be pure. They take props and state as input and return JSX — nothing more. This purity allows React to call your render function multiple times, abort renders in progress, or re-render components as needed without causing chaos.
The Problem with Render-Time Side Effects
When you run side effects during render, you break this contract. Imagine React as a careful architect creating blueprints (the virtual DOM) before construction begins. If workers start hammering nails and painting walls while the architect is still sketching, the blueprint becomes worthless — it no longer matches reality.
Here's what goes wrong:
React may call render multiple times: React can render your component, decide to discard that work (during concurrent rendering), and render again. If each render triggers a side effect like a network request or DOM manipulation, you'll get duplicate effects that can't be "undone."
Order becomes unpredictable: React doesn't guarantee the order components render in, and it might pause and resume rendering. Side effects during render would execute in random sequences.
State updates cause infinite loops: Setting state during render triggers another render, which triggers the side effect again, which triggers another render — an endless cycle that crashes your app.
The Solution
Side effects belong after render completes. That's exactly what the Effects Phase (coming with useEffect) is for — a safe, predictable time to interact with the outside world after React has finished its calculations.
Key Takeaway: Side effects during render break React's ability to safely call your component multiple times. Always defer side effects to after render using dedicated APIs like useEffect.