Navigate
Search topics, hooks, and fundamentals
React relies on immutable updates to detect changes. Like pottery that's been fired β you can't reshape it, you make a new one.
π‘ React uses Object.is() to detect changes. Without immutable updates, your state changes become invisible to React.
These are the patterns that trip up developers most often. Switch between Wrong and Fixed to compare the code side by side.
function TodoList() {
const [items, setItems] = useState(["Buy milk"]);
function addItem(text) {
items.push(text); // mutates the existing array!
setItems(items); // same reference β React skips re-render
}
function removeFirst() {
items.splice(0, 1); // mutates in place!
setItems(items);
}
}function Profile() {
const [user, setUser] = useState({ name: "Alice", age: 25 });
function handleBirthday() {
user.age += 1; // mutates existing object
setUser(user); // same reference β no re-render!
}
}function Settings() {
const [user, setUser] = useState({
name: "Alice",
address: { city: "NYC", zip: "10001" },
});
function updateCity(city) {
const newUser = { ...user };
newUser.address.city = city; // MUTATES user.address too!
setUser(newUser);
}
}