React Foundations · Robustness & DX

The Rules of React

The Rules of React

You have met most of React's rules already, one Lesson at a time. Together they are what let React's tools — the Compiler, Fast Refresh, Strict Mode — reason about your code. Break one and you get bugs that are hard to trace. The rules fall into a few groups.

Components must be pure. A render computes its JSX from props and state and changes nothing outside itself. Do not write to module-level variables during render, mutate props, or start fetches in render. Two renders with the same inputs must produce the same output; side effects belong in an effect or an event handler.

Hooks have rules. Call hooks only at the top level of a component or a custom hook — never inside a loop, a condition, or a nested function. React relies on the call order being the same on every render. Call them only from function components or custom hooks, not from plain JavaScript functions.

React owns the rendering. Do not mutate the values React gives you — props, state, or their contents. To change state, call the setter with a new value or a new copy: setItems([...items, next]).

Keys must be stable. Use a stable id from your data as a key, not the array index, so React can match items across renders.

Obey the rules and the Compiler can memoise your code, Strict Mode can check it, and Fast Refresh can keep your state while you edit.

You are about to answer a short quiz on the Rules of React.

  1. A component's render must be a pure function of its props and state.
  2. You may call hooks inside a loop or an if statement.
  3. Hooks must be called at the ___ level of a component or custom hook.
  4. Mutating a prop during render is allowed as long as the component still returns JSX.
  5. To add an item to state, call the setter with a new ___.