React Reference ยท Rules of React
Immutability of hook values
Why you must not mutate values returned from React hooks or arguments passed to them, with examples using state, useMemo and context, and the safe alternatives.
Once a value has been passed to a hook, or returned from one, React treats it as frozen. That covers the array in useState, the object a reducer returns, the result cached by useMemo, the value from useContext, the arguments you give to useEffect dependencies, and any value you pass into JSX. React compares these by reference and caches them between renders. If you change one in place, the cache holds the changed object and every comparison says "nothing changed".
This extends the rule for props and state to everything hooks hand back. The only values designed for mutation are the .current of a ref and the objects you create yourself during a render.
const [todos, setTodos] = useState(initial); const sorted = useMemo(() => todos.sort(byDate), [todos]); // wrong: mutates todos const sorted2 = useMemo(() => [...todos].sort(byDate), [todos]); // right: sorts a copy
Try it
Syntax
Where the rule applies:
| Value | Treat as read-only? | How to "change" it |
|---|---|---|
useState value |
Yes | Call the setter with a copy |
useReducer state |
Yes | Return a new object from the reducer |
useMemo / useCallback result |
Yes | Change the inputs; copy before modifying |
useContext value |
Yes | Change it in the provider's state |
| Arguments to a hook (initial value, dependency arrays) | Yes | Create new values |
| Values already used in JSX (props objects, children arrays) | Yes | Build a new element |
useRef().current |
No, mutate freely (outside render) | Assign to .current |
| Objects created inside the current render | No | Mutate before passing on |
Edge cases: passing a mutable object to a hook and then changing it later in the same render is also a violation, because React may already have stored it.
Usage notes
sort()is the classic offender, because it looks like it returns a new array but sorts in place. UsetoSorted()or copy first.- Memoization amplifies the damage.
useMemostores the reference you gave it, so a mutated input produces a cached output that never recalculates. - Effect dependencies compare by reference. An array you mutated and passed again has the same identity and the effect will not rerun.
- Context consumers are shared. One component mutating the context object changes it for every other consumer without notifying them.
- Freeze in development with
Object.freezeon initial data if you want mutations to throw loudly during testing. - The React Compiler assumes this rule when it caches values; code that mutates hook values can compile to incorrect output, and the compiler may skip it.
- Local copies are fine.
const copy = [...value]; copy.push(x);mutates your own copy, not the hook value.