Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 132 ยท Components and Props

Keeping Components Pure

Learn why React components must be pure functions, what breaks when render mutates outside values, how StrictMode exposes impurity and where side effects belong.

React asks one big thing of your components: be pure. A pure function does two things. It minds its own business, meaning it does not change anything that existed before it was called, and given the same inputs it always returns the same output. Components are pure functions of their props, their state and their context: same inputs, same JSX.

This sounds academic until you see why React insists on it. React may render a component more than once, may pause a render and throw it away, may render several components in a different order than you expect, and (in development) renders twice on purpose to catch mistakes. If a component's render has side effects, all of this turns into mysterious bugs. This lesson explains the rules, shows an impure component misbehaving, and tells you where side effects belong instead.

Pure functions in plain JavaScript

Compare two functions:

JavaScript
// Pure: same input -> same output, touches nothing else
function double(n) {
  return n * 2;
}

// Impure: depends on and changes something outside
let total = 0;
function addToTotal(n) {
  total = total + n;
  return total;
}

double(3) is always 6. addToTotal(3) returns 3, then 6, then 9: the same call gives different answers, and every call quietly changes a variable that other code may be reading. A recipe is a good picture of purity: if you follow the same recipe with the same ingredients you get the same dish, and following it does not alter the recipe book.

An impure component

Here is a component that numbers guests with a variable declared outside of it:

An impure component

At first the list says Guest #1, #2, #3. Each time you press Re-render the numbers jump to #4, #5, #6, then #7, #8, #9. The component has no props and no state, yet it renders differently every time, because each render modifies and reads the module-level guestCount. Nothing in the tree changed, but the output did.

The fix: let the parent pass in what differs. Now the output depends only on the props.

The same list, made pure

However many times you re-render, the list stays #1, #2, #3.

A purity test you can run

You can also check purity by hand: render an element twice with the same props and compare the output. renderToStaticMarkup from react-dom/server renders an element to an HTML string and works in the browser build, so it makes a tiny purity checker (StrictMode, next, does the same job automatically):

Render twice, compare the output

The console shows ImpureGuest is pure? false and PureGuest is pure? true. (The checker itself is only for learning; do not render components inside render in real code.)

StrictMode: React tests your purity for you

In development, wrapping your app in <StrictMode> makes React call each component function twice per render and discard one result. If the component is pure, the second call is invisible. If it is impure, the bug shows up the moment you write it. Our editor runs React's development build, so you can see it live. Here is the impure Guest inside <StrictMode>:

StrictMode exposes the impure component

You wrote three guests, so you expect #1, #2, #3. The page shows Guest #2, Guest #4, Guest #6, and the console has six Guest render lines (guestCount = 1 to 6): every component ran twice and React kept the second result. The skipped numbers are the symptom that tells you the component is impure. Delete <StrictMode> and the numbers return to 1, 2, 3, which is the trap: the bug was always there, only hidden.

JSX
// Read-only: how a project's entry file usually looks
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.jsx';

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <App />
  </StrictMode>
);

The extra render is a development-only behavior; production builds render once. StrictMode also runs every effect's setup and cleanup one extra time (Cleanup, Subscriptions and Timers). Always keep it on in development.

The rules of a pure component

Inside the render phase (the body of the component function, plus anything it calls), follow these rules:

  1. Mind your own business. Do not change objects or variables that existed before the render started.
  2. Same inputs, same output. Given the same props, state and context, return the same JSX. Do not read mutable outside values (Date.now(), Math.random(), a changing module variable) to decide what to show.
  3. Do not mutate your inputs. Props, state and context values are read-only snapshots (see Props and Objects and Arrays in State).
  4. Do not trigger side effects. No network requests, no timers, no DOM manipulation, no logging that matters, no calling a state setter of a component that is rendering.

Mutating props is the classic leak

Here the child sorts the array it receives. sort() mutates in place, so it also reorders the parent's data:

Sorting a prop mutates the parent's array

The first line, rendered before the child ran, says Original order: 30, 10, 20. The leaderboard says Top first: 30, 20, 10. And the footer, rendered after, reveals that the shared scores array itself now reads 30, 20, 10. One component's render silently changed data that other components read, so what the page shows depends on the order in which components happen to render. The repair is to copy before sorting:

JSX
const sorted = [...values].sort((a, b) => b - a);
// or: const sorted = values.toSorted((a, b) => b - a);

Local mutation is fine

Impurity means changing things that existed before render. A variable you create during the render and mutate only there is local and perfectly fine:

Local mutation during render is fine

The array is born and discarded inside one render call; nobody else can see it change. Calling the component again builds a fresh one, so the function stays pure.

Where do side effects go?

Real apps need side effects: fetching data, changing the document title, starting timers, saving to a server. They simply must not run during rendering. React gives them proper homes:

  • Event handlers. Most side effects respond to a user action (a click, a submit). Put them in the handler, which runs only when the event happens and is not part of rendering.
  • Effects (useEffect). For work that must happen because the component is on screen (subscribe to something, sync with a non-React system), use an effect, which runs after the render has been committed (Effects with useEffect).
  • Refs. Reading or writing ref.current during render is an impurity; do it in handlers or effects (Refs with useRef).
The side effect lives in the handler

The output paragraph is a pure function of name. The log runs only when you submit.

Why React cares: what purity buys you

  • Skipping and caching. If output depends only on inputs, React (and the React Compiler) can skip work when inputs did not change.
  • Concurrent rendering. React can start rendering, pause, and restart with new data (Transitions). Impure renders would leave half-applied side effects behind.
  • Server rendering. The same component runs on the server and in the browser. A component that reads window or a counter breaks hydration (Server-Side Rendering and Hydration).
  • Easier reasoning. You can look at one component, plug in props, and know what it shows.

Not everything is a pure function of props: reading Date.now() or Math.random() while rendering is impure even though it mutates nothing, since it breaks "same inputs, same output". Take the value in an event handler, an effect or from state instead, and keep render a function of its inputs.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which describes a pure component?

    Purity is about the render function: same inputs produce the same output, with no side effects on outside values.
  2. 2. What is wrong with the following component? let n = 0; function Item() { n++; return <li>{n}</li>; }

    Each render mutates and reads an outside variable. Re-renders, StrictMode double rendering and render order all change the output.
  3. 3. Which of these is allowed during render?

    Local mutation of values created during the render is fine. Sorting a prop mutates the caller's data, fetch is a side effect and refs belong in handlers or effects.
  4. 4. Where should a click-triggered save to the server be called?

    Handlers run only when the event happens and are not part of rendering, so they are the natural home for side effects.
  5. 5. What does StrictMode do in development to help you find impure components?

    The double render is invisible for pure components and exposes mutations of outside values for impure ones. It happens only in development builds.

Summary

  • A pure component returns the same JSX for the same props, state and context, and changes nothing that existed before the render.
  • Do not mutate outside variables, props or state during render. Copy first ([...items].sort(), toSorted).
  • Mutating values you create during the same render is fine.
  • Side effects belong in event handlers and effects, never in the render body.
  • StrictMode renders twice in development to expose impurity (an impure Guest shows #2, #4, #6 instead of #1, #2, #3).
  • Purity enables caching, concurrent rendering, server rendering and easy reasoning.

Next: Styling React Components