Sub topic 18
Common pitfalls and how to avoid them
This chapter assumes you know useState, event handlers, state snapshots, updater functions, and immutable updates for objects and arrays. It collects the mistakes that come up most often and shows how to fix each one.
Pitfall 1: Reading state right after setting it
A setter does not change the variable in the current render. The handler still sees the old snapshot.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
console.log(count); // still the old value
}
return <button onClick={handleClick}>{count}</button>;
}If you need the new value, compute it once in a local variable and use it for both the update and the next step.
const next = count + 1;
setCount(next);
console.log(next);Pitfall 2: Stacking updates that use the same snapshot
Calling setCount(count + 1) three times queues three updates that all say "set to 1". Use an updater function when the next value depends on the previous one: setCount(c => c + 1).
Pitfall 3: Mutating state
Calling push, splice, or assigning to person.name changes the existing object. React compares the old and new values by reference, so it can skip the re-render. Create a new object or array with spread, map, or filter.
| Mutating (avoid) | Non-mutating (use) |
|---|---|
| `todos.push(item)` | `[...todos, item]` |
| `todos.splice(i, 1)` | `todos.filter(t => t.id !== id)` |
| `person.name = 'Ana'` | `{ ...person, name: 'Ana' }` |
| `todos.sort()` | `[...todos].sort()` |
Pitfall 4: Copying props or derived data into state
If you write useState(props.value), the state only uses the prop on the first render. Later prop changes are ignored. The same problem appears when you store a filtered list in state next to the full list. Compute values during render instead, as the Filter example did with visible. If you really need a fresh start when a prop changes, give the component a key.
Pitfall 5: Unstable list keys
Using the array index as a key breaks state when items are inserted, removed, or reordered. State such as a checked box stays with the position, not the item. Use a stable id.
Pitfall 6: Calling a handler instead of passing it
onClick={setCount(1)} runs during render and triggers another render, which causes an infinite loop. Pass a function: onClick={() => setCount(1)}.
Exercise
Exercise
A component keeps items in state and a second state variable count that it updates with setCount(items.length) after every change. Sometimes count is wrong. What is the fix?
Show answer
Remove the count state and compute const count = items.length; during render. A value that can be derived from other state should not be stored, because two copies can drift apart.
Exercise
Why does setTodos(todos.sort()) often fail to re-render, and what should you write instead?
Show answer
sort mutates the existing array and returns the same reference, so React sees no change. Write setTodos([...todos].sort()) to sort a copy.