React Best Practices

Chapter 1 · Practice 1 of 5

Keep components pure during render

From Components and purity

Why it matters

React may render a component more than once, pause a render, or throw one away. If your render body has side effects, they run at unpredictable times, which is why purity is the rule everything else depends on.

A component should behave like a formula: same props, state and context in, same JSX out. While rendering:

  • Do not change variables that existed before the render.
  • Do not mutate props.
  • Do not start network requests or write to storage.

Put side effects in event handlers first, and in effects only when there is no event to attach them to.

Do

  • Create new objects and arrays inside the render instead of changing shared ones
  • Move writes, requests and timers into event handlers or effects
  • Keep Strict Mode on in development to catch impure renders

Avoid

  • Pushing into an array declared outside the component
  • Reading Math.random() or Date.now() in render for values that must stay stable

Example

TSX
// Impure: mutates a value that lives outside the render
const seen: string[] = [];
function Tag({ name }: { name: string }) {
  seen.push(name);
  return <li>{name}</li>;
}

// Pure: output depends only on props
function TagList({ names }: { names: string[] }) {
  const sorted = [...names].sort();
  return <ul>{sorted.map((n) => <li key={n}>{n}</li>)}</ul>;
}