Sub topic 18
Common pitfalls and how to avoid them
This chapter assumes you can write function components, pass props, and use spread syntax and the map and filter array methods. It also assumes you have met useState, state snapshots, updater functions, and immutable updates in earlier chapters. Here those ideas become a checklist of mistakes, each with its symptom and its fix.
Most useState bugs come from two facts. State in a render is a fixed snapshot, and React only re-renders when it receives a new value. Nearly every pitfall below breaks one of those two facts.
A way to diagnose state bugs
Start from the symptom, then look for the cause.
Reading state right after setting it
The setter does not change the variable in the current render. It schedules a new render. Code after the call still sees the old snapshot.
import { useState } from 'react';
function Demo() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
console.log(count); // logs the old value, not count + 1
}
return <button onClick={handleClick}>{count}</button>;
}If you need the next value in the same handler, compute it once and use it twice.
function handleClick() {
const next = count + 1;
setCount(next);
console.log(next);
}Repeating the same non-functional update
Calling setCount(count + 1) three times queues three requests for the same value, so the count rises by 1. When an update depends on the previous state, pass an updater function: setCount(c => c + 1). React runs queued updaters in order, and each one receives the result of the one before.
Updater functions must be pure. They should return a value computed from their argument and should not change anything outside themselves. In Strict Mode during development, React calls them twice to expose impurity.
Stale values in delayed code
Timeouts, intervals, and promise callbacks capture the snapshot from the render that created them. If a user clicks, then clicks again before a timer fires, the timer still sees the old value.
import { useState } from 'react';
function DelayedCounter() {
const [count, setCount] = useState(0);
function addLater() {
setTimeout(() => {
setCount(c => c + 1); // uses the latest pending value
}, 2000);
}
return <button onClick={addLater}>Add later ({count})</button>;
}Writing setCount(count + 1) inside the timeout would use the count from the click's render. Several quick clicks would then collapse into a single increment.
Mutating state and expecting a re-render
React compares the new value to the old one with Object.is. If you push to an array and pass the same array back, the references match and React may skip the update.
// Wrong: same array reference
function addWrong(item) {
items.push(item);
setItems(items);
}
// Right: new array
function add(item) {
setItems([...items, item]);
}Nested objects need the same care at every level you change. A shallow copy leaves inner objects shared with the old state.
import { useState } from 'react';
function Address() {
const [user, setUser] = useState({
name: 'Ada',
address: { city: 'London', zip: 'N1' },
});
function moveWrong() {
const copy = { ...user };
copy.address.city = 'Paris'; // mutates the shared inner object
setUser(copy);
}
function move() {
setUser({ ...user, address: { ...user.address, city: 'Paris' } });
}
return <button onClick={move}>{user.address.city}</button>;
}moveWrong changes the old state's address too. That breaks any code that compares old and new values, and it can leave memoized children showing stale data. If nesting becomes painful, flatten the state shape instead of writing deeper spreads.
Expecting setState to merge objects
Class components merged partial updates. useState replaces the whole value.
const [person, setPerson] = useState({ name: 'Ada', email: '[email protected]' });
setPerson({ name: 'Grace' }); // email is now gone
setPerson({ ...person, name: 'Grace' }); // email is keptIf fields change independently, you can also use separate useState calls for each one.
Calling the handler instead of passing it
// Wrong: runs during render, sets state, triggers a render, repeats
<button onClick={setCount(count + 1)}>Add</button>
// Right: passes a function that React calls on click
<button onClick={() => setCount(count + 1)}>Add</button>The wrong version produces the error "Too many re-renders". The same loop happens if you call a setter unconditionally in the component body. Setting state during render is only valid as a guarded pattern, such as adjusting state when a prop changes. Most other code belongs in an event handler.
Copying props into state
import { useState } from 'react';
function Greeting({ name }) {
const [text, setText] = useState(name); // read only on the first render
return <input value={text} onChange={e => setText(e.target.value)} />;
}The initial value is used once. If the parent later passes a different name, text does not follow it. Pick the behavior you want:
- If the prop is only a starting value, name it
initialNameso the intent is clear. - If the value should always match the prop, do not store it. Use the prop directly.
- If the component should restart for a new entity, give it a
key, such as<Greeting key={userId} name={name} />.
Storing values you can compute
Keeping items and visibleItems in two state variables means every change must update both. Miss one place and they disagree. Store the minimum, and compute the rest during render. The same applies to a selected object. Store its id and look the object up in the list, so edits to the list are reflected automatically.
Using array indexes as keys
When items can be added, removed, or reordered, key={index} ties each item's state to a position. Delete the first row, and the second row's checkbox state or input text moves to the wrong item. Use an id that comes with the data, or assign one when you create the item, as the todo example earlier did. Indexes are acceptable only for lists that never change order or length.
Putting expensive work in the initial value
useState(JSON.parse(localStorage.getItem('cart'))) parses storage on every render, even though React ignores the result after the first one. Pass a function instead: useState(() => JSON.parse(localStorage.getItem('cart')) ?? []). Pass the function itself, not its result. Writing useState(readCart()) calls it every render.
The reverse mistake is storing a function as state. setFn(myFunction) makes React call myFunction as an updater. To store a function, wrap it: setFn(() => myFunction).
Quick reference
| Symptom | Likely cause | Fix |
|---|---|---|
| Logged value is one step behind | Reading the snapshot after calling the setter | Use a local `next` variable |
| Three updates add only 1 | Repeated `count + 1` | Use `c => c + 1` |
| UI does not change | Mutated state or reused the reference | Build a new array or object |
| Fields vanish after an update | Partial object replaced the state | Spread the old object first |
| "Too many re-renders" | Setter called during render | Pass a function to the event prop |
| Prop change ignored | Prop copied into state | Use the prop, or add `key` |
| Wrong row keeps its input text | Index used as key | Use stable ids |
Exercise
A component keeps const [tags, setTags] = useState(['a']). A handler runs tags.push('b'); setTags(tags);. The list on screen does not change. Why, and what is the fix?
Show answer
push mutates the existing array, and setTags receives the same reference, so React sees no change and skips the re-render. Create a new array instead: setTags([...tags, 'b']).
Exercise
A button has onClick={setOpen(!open)} and the app crashes with "Too many re-renders". What is wrong, and how do you fix it?
Show answer
setOpen(!open) runs during render, which schedules another render that runs it again, in a loop. Pass a function instead: onClick={() => setOpen(!open)}.