Capítulo 114 de 116

Chapter 114: Rules of React — Components and Hooks Must Be Pure

Core Idea

This is the formal statement of the purity rule practiced throughout Ch 18/22: components and Hooks must behave like pure functions of their inputs — same props/state/context in, same result out, no mutation of anything that existed before the call — because React's entire optimization and correctness model (memoization, Strict Mode, concurrent rendering, and the Compiler) depends on that guarantee holding.

Key Concepts

  • Idempotency: calling the same component with the same props/state/context must always produce the same JSX — order of calls, number of calls, or timing must not affect the result.
  • No side effects during render: side effects (mutating outside variables, network requests, subscriptions, direct DOM manipulation) belong in event handlers or Effects (Ch 36), never in the render body itself — this is the concrete rule Ch 18 introduced with the guest counter example.
  • Props, state, and context are all treated as immutable snapshots during a given render (Ch 23) — reading them is fine; writing to them directly is a purity violation.
  • Local mutation is exempt: creating and mutating a variable that only exists within the current render call (e.g. building up a local array before returning JSX) doesn't violate purity — the rule is about not touching anything that predates this specific render.
  • Why this matters beyond "good practice": React Compiler (Ch 42), Strict Mode's double-invoke (Ch 69), memoization (memo/useMemo/useCallback), and concurrent features can all call, discard, or re-call component/Hook functions in ways an impure function would misbehave under — purity isn't a style preference, it's a load-bearing assumption of the whole rendering model.

Key Takeaways

  1. This chapter formalizes exactly what Ch 18 taught practically — read that chapter first for the intuition, this one for the precise rule statement.
  2. Every optimization feature in modern React (Compiler, memoization, Strict Mode, concurrent rendering) silently assumes this rule holds — violating it doesn't just risk a bug today, it risks a bug appearing/disappearing as unrelated optimizations are adopted later.
  3. The eslint-plugin-react-hooks purity rule (Ch 47) mechanically catches many violations of this exact rule.

Connects To

  • Ch 18 (Keeping Components Pure): the practical, worked-example version of this rule.
  • Ch 42 (React Compiler — Introduction): the primary reason this rule's importance has grown — the compiler's optimizations rely on it holding.
  • Ch 47 (ESLint Rules Reference): the purity rule that enforces this mechanically.