Sub topic 4
The Rules of React the Compiler Depends on
This chapter assumes you know function components, props, state, useEffect, and why React re-renders a component. It also assumes you have seen useMemo and useCallback.
Why the compiler needs rules
The compiler decides at build time which values it can cache between renders. Caching is only safe if a component returns the same output for the same props, state, and context. The Rules of React describe code that behaves this way.
When your code follows the rules, the compiler can skip work without changing what the user sees. When it doesn't, the compiler usually detects the problem and skips that component or hook. This is called a bailout. Some violations can't be detected, and then cached output may be stale. That is why the rules matter even before you install the compiler.
Rule 1: Rendering must be pure
A pure component gives the same output for the same inputs and changes nothing that existed before the render began. You may create and change local values inside the function. You must not change props, outer variables, or objects passed in.
// Breaks the Rules of React: mutates a prop during render.
function Bad({ items }) {
items.sort();
return <ul>{items.map((i) => <li key={i}>{i}</li>)}</ul>;
}
// Fixed: copy first, then sort the copy.
function Good({ items }) {
const sorted = [...items].sort();
return <ul>{sorted.map((i) => <li key={i}>{i}</li>)}</ul>;
}Bad reorders the parent's array on every render. If the compiler cached its result, the order would depend on how often it ran. Good only changes an array it created itself.
Avoid Math.random(), Date.now(), and reads of mutable outer variables in the render body. Their results change between renders even when the inputs do not.
Rule 2: Props and state are immutable
Treat props and state as read-only snapshots. To change state, call the setter with a new value. The compiler compares references to decide whether a cached value is still valid, and an in-place mutation keeps the old reference.
import { useState } from 'react';
export function Todos() {
const [todos, setTodos] = useState([]);
function add(text) {
// Wrong: todos.push(text) keeps the same array reference.
setTodos([...todos, text]);
}
return (
<>
<button onClick={() => add('Write tests')}>Add</button>
<ul>
{todos.map((t, i) => <li key={i}>{t}</li>)}
</ul>
</>
);
}Rule 3: Side effects belong outside render
Render code only calculates what the screen should look like. Put work that affects anything else, such as network calls, subscriptions, or writes to a ref, in an event handler or an effect.
Reading or writing ref.current during render also breaks the rules, because a ref is a mutable box that React does not track. Read it in handlers and effects.
Rule 4: Call hooks in the standard way
Call hooks only at the top level of a component or custom hook. Don't call them inside conditions, loops, or nested functions. The compiler relies on a stable call order to match each cached value to its slot.
Quick reference
| Violation | Typical symptom | Fix |
|---|---|---|
| Mutating a prop in render | Parent data changes unexpectedly | Copy, then change the copy |
| Mutating state directly | UI does not update | Pass a new value to the setter |
| Reading `Math.random()` in render | Output differs on each render | Compute it in state or an effect |
| Writing `ref.current` in render | Inconsistent values | Move it to a handler or effect |
| Conditional hook call | Hook order errors | Move the condition inside the hook |
What to do when you find a violation
Fix the cause when you can, as in Good above. If you can't fix it yet, a later chapter shows how to opt a single component out with the 'use no memo' directive. The lint rules covered in a later chapter report these violations for you.
Exercise
This component sorts a prop inside render. Explain why the compiler can't safely memoize it, and write the fixed line. function Names({ list }) { list.reverse(); return <p>{list.join(', ')}</p>; }
Show answer
list.reverse() changes the array in place, and the array belongs to the parent. Each render flips the order again, so the output depends on how many times the component ran, which breaks purity. Caching the result would give a different answer than re-rendering. The fix is to copy first: const reversed = [...list].reverse(); and then render reversed.join(', ').