Pure Functions vs Side Effects
What You'll Learn: You'll discover why React components must behave like pure functions during rendering, and where side effects belong in your component lifecycle.
What is a Pure Function?
A pure function follows two simple rules:
- Same inputs → same output: Given the same props and state, it always returns the same JSX
- No side effects: It doesn't modify external variables, call APIs, or change the DOM directly
Think of a pure function like a recipe. If you use the same ingredients (inputs), you get the same dish (output) every time. The recipe doesn't order groceries or rearrange your kitchen — it just describes what to make.
Why React Components Must Be Pure During Render
React's rendering process assumes your component is predictable. When React calls your component function, it expects to receive JSX based solely on the current props and state. This allows React to:
- Re-render components multiple times safely
- Pause and resume rendering without consequences
- Optimize by skipping unnecessary renders
// ✅ Pure component
function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}
// ❌ Impure — modifies external state during render
let renderCount = 0;
function BadGreeting({ name }) {
renderCount++; // Side effect!
return <h1>Hello, {name}!</h1>;
}
Where Side Effects Belong
Side effects like data fetching, subscriptions, or manual DOM changes must happen outside the render phase. They belong in:
- Event handlers (like
onClick) useEffect(which runs after render)
Key Takeaway: React components should be pure functions during render — they calculate what to display without changing anything. Side effects must be deliberately placed in event handlers or effects where React can manage them safely.