Course contentsShow
← React
Lesson 407 of 2,39612. Rendering and BatchingFree lesson

Pure Functions: Why Components Must Be Pure

Components should return the same JSX given the same props/state—side effects break React's ability to optimize rendering.

Pure Functions: Why Components Must Be Pure

You'll learn: Why React components must behave like pure functions—returning the same JSX for the same inputs every time.

What is a Pure Function?

A pure function is one that:

  1. Always returns the same output for the same inputs (predictable)
  2. Doesn't modify variables outside its scope (no side effects)

Think of a pure function like a vending machine: you press B3, you get chips. Every single time. It doesn't randomly give you pretzels, and it doesn't unlock someone else's locker while dispensing your snack.

Why React Components Must Be Pure

React assumes your component is a pure function during the render phase. Given the same props and state, your component should return the same JSX. This assumption allows React to:

  • Skip re-renders when props/state haven't changed (optimization)
  • Render components in any order or even render them multiple times without breaking your app
  • Pause, abort, or restart rendering without side effects leaking out

If your component modifies external variables, makes network requests, or changes the DOM during render, React can't optimize safely. You've broken the contract.

The Danger of Impurity

let guest = 0; // External variable

function Guestbook() {
  guest = guest + 1; // ❌ IMPURE: modifying outside variable during render
  return <h1>Guest #{guest}</h1>;
}

React might call Guestbook multiple times during one update cycle. Now guest is wrong. Your UI lies.

Side effects belong in event handlers or useEffect, not render logic.

Key Takeaway: Components must be pure functions—same props/state always produces same JSX—so React can optimize and batch renders safely without breaking your app.