Home / Learn React / The Rules of React

The Rules of React

React works best when components are pure and hooks are called in a fixed way. These rules also let the compiler and StrictMode help you.

In shortKeep components pure, never change props or state directly, call hooks only at the top level of components and custom hooks.

Theory in plain words

Rules at a glanceRender must be pure: no random numbers, dates or mutation in the bodyNever mutate props or state: create a new copySide effects belong in handlers and useEffectHooks only at the top level, never in if, loops or after returnHooks only from components or custom hooks
Rules at a glance

What it is

The Rules of React are a small set of conventions: components and hooks must be pure (same input, same output), props and state are read-only, and hooks are called unconditionally at the top level.

Why we use it

React may render a component more than once, pause it or skip it. That only works safely if rendering has no hidden side effects. Following the rules makes bugs rare and lets tools optimize your code.

How it works

During render, calculate and return JSX. Do side effects (network, timers, DOM changes) in event handlers or useEffect. Update state by creating new objects and arrays.

Where it is used

  • Every React codebase, and a requirement for React Compiler

Mutation bug

Why not to mutate stateTry it Yourself

Click the wrong button: nothing changes on screen. Click the right button: you see the new items and also the ones pushed earlier, because the data had changed but React did not re-render.

Pure render

Impure vs pureTry it Yourself

In StrictMode, React renders twice on purpose, so the impure component skips a number. That is how StrictMode exposes the problem.

Quick quiz

1. What should a component do while rendering?

2. Where can hooks be called?

3. Why does list.push(x); setList(list) fail?

Common questions

What should a component do while rendering?

Be pure and only calculate JSX. Same input, same output.

Where can hooks be called?

At the top level of components and custom hooks. Never conditionally.

Why does list.push(x); setList(list) fail?

The array reference did not change. Create a new array.