Sub topic 4
The Rules of React the compiler depends on
This chapter explains the contract between your code and the React Compiler. It assumes you know function components, props and state, and the useState, useEffect, useMemo and useCallback hooks. You should also know in general terms why React re-renders a component.
Why the compiler needs rules
The compiler adds memoization (caching) to your components at build time. To cache a value safely, it must be sure that the same inputs always produce the same output, and that skipping a call changes nothing visible. If a component changes outside data while it renders, skipping that render would change program behavior.
React has long documented a set of rules that make components safe to re-run, skip, or run in a different order. The compiler does not invent new rules. It relies on these existing ones and assumes your code follows them.
If your code breaks a rule, the compiler can do one of two things:
- Skip the component or hook and leave it as written (a bailout).
- In the worst case, compile code it wrongly believed to be safe, which can produce stale or incorrect UI.
Following the rules is what makes the first outcome the common one and the second one rare.
The rules at a glance
| Rule | What it means | Typical violation |
|---|---|---|
| Components and hooks are pure | Same props, state and context give the same JSX | Reading `Math.random()` or `Date.now()` during render |
| Props and state are immutable | Never change them directly | `items.sort()` on a prop |
| Side effects run outside render | Use event handlers or `useEffect` | Writing to a global variable while rendering |
| Values are immutable after use | Do not change a value after passing it to JSX or a hook | Mutating an object after putting it in JSX |
| Hooks are called at the top level | Not in loops, conditions or nested functions | `if (x) useState(0)` |
| Components are called by React | Render with JSX, not by calling `Component()` | `{Child({ a: 1 })}` |
Rule 1: Rendering must be pure
A pure function returns the same result for the same inputs and does nothing else. For a component, the inputs are props, state and context. The output is the JSX it returns.
Compare these two components:
import { useState } from 'react';
let renderCount = 0;
// Impure: output depends on a changing outside value,
// and render changes that value.
function Impure({ label }) {
renderCount += 1;
return <p>{label} rendered {renderCount} times</p>;
}
// Pure: output depends only on props and state.
function Pure({ label }) {
const [clicks, setClicks] = useState(0);
return (
<button onClick={() => setClicks(clicks + 1)}>
{label}: {clicks}
</button>
);
}Impure changes renderCount while rendering. If the compiler caches its JSX because label did not change, the count stops updating. The cached output no longer matches what the code says it should produce. React also has no guarantee about how many times it renders a component, so counting renders this way is unreliable even without the compiler.
Local mutation is fine. A value created during the current render and never shared can be changed freely:
function Tags({ tags }) {
const labels = [];
for (const tag of tags) {
labels.push(tag.toUpperCase());
}
return <p>{labels.join(', ')}</p>;
}Here labels is created and finished inside one render. Nothing else can observe the change, so the component is still pure.
Rule 2: Props and state are immutable
Treat props and state as read-only. To change state, call the setter. To change a prop-derived value, make a copy.
The topic's example shows the most common mistake. Sorting an array in place changes the array that the parent owns:
// 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>;
}In Bad, the parent's array is reordered on every render. The reference to items stays the same, so a memoized check such as "did items change?" says no, even though the contents did. In Good, the original is untouched.
The same applies to state. This is wrong:
import { useState } from 'react';
function Todos() {
const [todos, setTodos] = useState([]);
function addBad(text) {
todos.push({ text }); // mutates state
setTodos(todos); // same reference, React sees no change
}
function addGood(text) {
setTodos([...todos, { text }]); // new array
}
return (
<button onClick={() => addGood('write')}>Add ({todos.length})</button>
);
}addBad keeps the same array reference, so React and the compiler both treat the state as unchanged. Compiled code decides whether to reuse a cached value by comparing references, so in-place mutation defeats it.
Rule 3: Side effects do not belong in render
A side effect is anything that reaches outside the function: changing a global, writing to the DOM, sending a request, logging to an external service, or changing a ref.
Put side effects in one of two places:
- An event handler, for work caused by a user action.
useEffect, for work that must happen because the component appeared or a value changed.
Refs need special care. Reading or writing ref.current during render is unsafe because React may render a component more than once, or discard a render. The compiler's analysis treats this as a violation. Do it in an event handler or an effect instead.
import { useEffect, useRef } from 'react';
function Timer({ onTick }) {
const intervalRef = useRef(null);
useEffect(() => {
intervalRef.current = setInterval(onTick, 1000);
return () => clearInterval(intervalRef.current);
}, [onTick]);
return <p>Running</p>;
}The ref is written inside the effect, not during render. That is allowed.
Rule 4: Do not change values after using them
Once you pass a value to JSX, to a hook, or return it from a hook, treat it as frozen. The compiler can cache JSX that contains the value. A later change would not appear in the cached output.
function Bad({ user }) {
const style = { color: 'red' };
const element = <p style={style}>{user.name}</p>;
style.color = 'blue'; // changes a value already used in JSX
return element;
}
function Good({ user }) {
const style = { color: 'blue' };
return <p style={style}>{user.name}</p>;
}Finish building a value first, then use it.
Rule 5: Hooks have fixed call order
React identifies each hook by the order of the calls. Call hooks only at the top level of a component or a custom hook, and only from those places.
import { useState } from 'react';
// Wrong: the call is conditional.
function Bad({ show }) {
if (show) {
const [open, setOpen] = useState(false);
}
return null;
}
// Right: call first, then decide what to do.
function Good({ show }) {
const [open, setOpen] = useState(false);
if (!show) return null;
return <button onClick={() => setOpen(!open)}>{String(open)}</button>;
}Compiled code stores its cached values in a slot array that is tied to the same stable call structure. Conditional hooks break that structure.
Rule 6: Let React call your components
Do not call a component as a plain function, and do not pass hooks around as ordinary values. Use JSX, so React can manage state, order and re-rendering for each instance.
function Avatar({ name }) {
return <span>{name[0]}</span>;
}
function Bad() {
return <div>{Avatar({ name: 'Ada' })}</div>; // runs inside Bad's render
}
function Good() {
return <div><Avatar name="Ada" /></div>;
}If Avatar used a hook, Bad would silently attach that hook's state to Bad.
How the rules connect to caching
The next diagram shows the decision the compiler makes for each component.
A skipped component still works. It just keeps re-rendering the way it did before. The compiler is designed to be conservative: when it cannot prove a function is safe, it leaves it alone.
Not every violation can be detected. Static analysis only sees code, not runtime behavior. A function that mutates a value through several layers of helper calls, or through a third-party library, may pass analysis and still misbehave. This is why the next chapters cover lint rules and DevTools checks instead of trusting the compiler alone.
Common mistakes
- Mutating a prop "just for sorting". Copy it first.
- Storing derived data in a module-level variable that render reads and writes.
- Reading
ref.currentto compute JSX. Use state if the value must affect what is shown. - Calling
new Date()orMath.random()in render and expecting a new value each render. The compiler may cache the result. Generate such values in state, an effect or an event handler. - Assuming that code which "works today" is safe. Without the compiler, extra re-renders often hide a violation. Caching exposes it.
Exercises
Exercise
This component sorts its scores prop in place. Rewrite the line so the component follows the Rules of React, and explain why the original is a problem for compiler-based memoization.
function Leaderboard({ scores }) {
scores.sort((a, b) => b - a);
return <ol>{scores.map((s) => <li key={s}>{s}</li>)}</ol>;
}
Show answer
Use const sorted = [...scores].sort((a, b) => b - a); (or scores.toSorted(...)) and map over sorted. The original changes the parent's array while rendering. The array reference stays the same while its contents change, so any cache that compares references sees "no change" and may reuse stale output. Mutating a prop also breaks the immutability rule.
Exercise
A component writes ref.current = props.value in its function body and reads ref.current in the JSX. Which rule does this break, and where should the write move?
Show answer
It breaks the rule that side effects must not run during render, since refs are not part of the render inputs. Move the write into useEffect or an event handler. If the displayed value must update the UI, store it in state instead of a ref.