← Back to React, page 6

react-0114 · Easy fresher

What does it mean for a React component to be pure, and which things count as side effects in render?

A pure component returns the same output for the same props, state and context, and changes nothing outside itself while rendering. Side effects in render include mutating variables created outside the component, writing to the DOM, sending requests, starting timers, and reading changing values such as Date.now() or Math.random() for output. Put side effects in event handlers or effects. Strict Mode renders twice in development to expose impurity.

Full answer

React may call your component function more than once, in any order, and sometimes throw the result away (Strict Mode, concurrent rendering, Suspense retries). That is only safe if rendering is pure, like a math function: the same inputs always give the same output, and nothing else is changed.

What purity allows: reading props, state and context, creating new local values (objects, arrays), calling pure helpers and returning JSX. Creating values during render is fine, even when they are mutated afterwards, as long as they were created in the same render. Mutating something that existed before the render started is not fine.

Side effects in render (avoid):

  • Changing a variable declared outside the component (a module-level counter or array).
  • Mutating props, state or context objects directly.
  • Writing to the DOM, document.title, localStorage, or logging to analytics.
  • Starting timers, subscriptions or network requests.
  • Output that depends on unstable sources: Math.random(), Date.now(), new Date() without being passed in.

Where effects belong. User-caused changes go in event handlers. Changes needed because the component appeared on screen or because a value changed go in useEffect, which runs after rendering. Synchronization with the DOM before paint uses useLayoutEffect.

Detection. Strict Mode calls component functions twice in development and compares the result expectations. An impure component shows visible bugs, such as a counter that jumps by two. Linting also helps (eslint-plugin-react-hooks and the React Compiler lint rules).

Why it matters beyond correctness. Purity lets React skip renders, reuse results, render in the background and enable the Compiler to memoize safely.

The example renders a component that uses an outer counter and another that gets the value as a prop, in Strict Mode.

jsx
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';

let guestCount = 0;

function ImpureGuest() {
  guestCount += 1;
  return <li>Impure guest #{guestCount}</li>;
}

function PureGuest({ number }) {
  return <li>Pure guest #{number}</li>;
}

const container = document.getElementById('root');
createRoot(container).render(
  <StrictMode>
    <ul>
      <ImpureGuest />
      <ImpureGuest />
      <PureGuest number={1} />
      <PureGuest number={2} />
    </ul>
  </StrictMode>
);

await new Promise((resolve) => setTimeout(resolve, 30));
console.log(container.textContent);

The script rendered the tree inside Strict Mode. The impure component changes an outer variable, so each call counts and the numbers skip. The pure one always shows what it was given. Output of the run: Impure guest #2Impure guest #4Pure guest #1Pure guest #2

Key points

  • Pure components give the same output for the same inputs and change nothing outside themselves.
  • Creating and mutating new local values during render is fine. Mutating pre-existing values is not.
  • Side effects belong in event handlers or effects, not in render.
  • Unstable inputs such as Date.now and Math.random make render impure.
  • Strict Mode double rendering and linting help detect impurity.

Common mistakes

  • Changing module-level variables during render.
  • Using Math.random or Date.now directly in the returned JSX.
  • Fetching data or setting timers in the component body.
  • Mutating props or state objects.
  • Disabling Strict Mode to hide the symptoms.

Follow-ups

  • Why is mutating an object created in the same render acceptable?
  • Where would you put the work that updates document.title?
  • How does the React Compiler depend on purity?

Tips

  • Describe components as math functions.
  • Say that mutating new local values is fine and give the distinction.
  • Point to Strict Mode as the detector.