React detects changes by reference equality (Object.is), not by deep comparison. If you mutate an object or array and pass the same reference to the setter, React may skip the re-render entirely. Even when something else triggers a render, mutation breaks memo, useMemo, effect dependencies and the React Compiler, corrupts previous-render snapshots (closures, transitions, DevTools), and makes concurrent rendering unsafe. Treat state as immutable: create new objects or arrays with the change.
function TodoList() {
const [todos, setTodos] = useState([]);
function add(text) {
todos.push({ id: crypto.randomUUID(), text }); // mutation
setTodos(todos); // same reference, so React bails out
}
}
Object.is(todos, todos) is true, so React considers the state unchanged and may skip rendering. The UI is stuck until an unrelated update happens, then suddenly "catches up". These are confusing, intermittent bugs.
function add(text) {
setTodos(prev => [...prev, { id: crypto.randomUUID(), text }]);
}
prev !== next is O(1). This powers memo, useMemo/useCallback dependencies, useEffect dependencies, context propagation, and external-store selectors.// Object field
setUser(u => ({ ...u, name: 'Ada' }));
// Nested
setUser(u => ({ ...u, address: { ...u.address, city: 'Pune' } }));
// Arrays
setItems(xs => [...xs, item]); // add
setItems(xs => xs.filter(x => x.id !== id)); // remove
setItems(xs => xs.map(x => x.id === id ? { ...x, done: true } : x)); // update
setItems(xs => xs.toSorted(compare)); // sort without mutating (ES2023)
Watch for mutating methods: push, splice, sort, reverse, and direct assignment (obj.x = 1). ES2023 adds non-mutating versions: toSorted, toReversed, toSpliced, with.
Immer lets you write "mutating" code against a draft and produces an immutable result, which is useful for deep updates:
setUser(produce(draft => { draft.address.city = 'Pune'; }));
{ ...state } still shares state.address.ref.current is meant to be mutated, but it won't trigger renders.Object.is reference comparison means mutation equals "no change".Spotted a mistake or a rights concern? Report an issue