Sub topic 13
Common Pitfalls and How to Debug Them
This chapter assumes you have already lifted state into a parent. You know how to pass a value and a callback to children, and you have built a controlled input. Here you will learn the mistakes that show up most often after that, how to recognize each one from its symptom, and how to fix it.
Start from the symptom
Most lifting bugs fall into a small number of causes. Work from what you see to where to look.
| Symptom | Likely cause | Where to look |
|---|---|---|
| A child ignores a change made by the parent | The child copied a prop into its own state | `useState(props.something)` in the child |
| Console warning about switching from uncontrolled to controlled | The input's `value` was `undefined` at first | The initial value passed to `useState` |
| A comparison like `size === 3` is never true | A string from an event is compared with a number | The `onChange` handler |
| "Too many re-renders" error | A handler was called during render instead of passed | JSX props like `onClick={fn()}` |
| State changes but the screen does not update | State was mutated in place | `push`, `splice`, or assignment on a state object |
| Every keystroke re-renders a huge tree | State was lifted higher than needed | The component that owns the state |
Pitfall 1: copying a prop into state
This is the most common way to break single-source-of-truth. A child receives value as a prop and then uses it to initialize its own state.
import { useState } from 'react';
function Field({ label, value, onChange }) {
// Bug: the prop is read once, on the first render only.
const [text, setText] = useState(value);
return (
<label>
{label}:{' '}
<input
value={text}
onChange={e => {
setText(e.target.value);
onChange(e.target.value);
}}
/>
</label>
);
}
export default function App() {
const [text, setText] = useState('hello');
return (
<>
<Field label="First" value={text} onChange={setText} />
<Field label="Second" value={text} onChange={setText} />
<button onClick={() => setText('')}>Reset</button>
</>
);
}Typing works, because each field updates its own copy and also tells the parent. Reset does not work. The parent sets text to an empty string, but useState(value) ignores the new prop after the first render. Both fields keep their old text. There are now three copies of the truth: the parent's and one in each child.
The fix is to delete the child's state and read the prop directly.
function Field({ label, value, onChange }) {
return (
<label>
{label}: <input value={value} onChange={e => onChange(e.target.value)} />
</label>
);
}Pitfall 2: `undefined` values and the controlled/uncontrolled warning
An input is controlled when its value prop is not undefined. If the value starts as undefined and later becomes a string, React warns that the component changed from uncontrolled to controlled. This usually happens when state is declared without an initial value, or when it is filled from data that has not arrived yet.
import { useState } from 'react';
export default function NameForm() {
// Bug: useState() starts as undefined.
// Fix: useState('')
const [name, setName] = useState();
return <input value={name} onChange={e => setName(e.target.value)} />;
}Use '' for text inputs and false for checkboxes (which use checked instead of value). If a value comes from loaded data, write value={user.name ?? ''}.
Pitfall 3: mismatched value types
Every DOM event value is a string, even from <input type="number"> and from a <select> whose options look numeric. The parent's logic often expects a number.
import { useState } from 'react';
const PRICES = { 1: 3, 2: 5, 3: 8 };
export default function SizePicker() {
const [size, setSize] = useState(2);
return (
<>
<select
value={size}
onChange={e => setSize(Number(e.target.value))}
>
<option value={1}>Small</option>
<option value={2}>Medium</option>
<option value={3}>Large</option>
</select>
<p>Price: {PRICES[size]}</p>
{size === 3 && <p>Large includes a free refill.</p>}
</>
);
}Without Number(...), size becomes the string '3' after the first change. PRICES['3'] still works because object keys are strings, which hides the bug. The size === 3 check silently fails. Convert at the boundary, in the handler, so the state always holds one type.
The temperature converter from earlier follows the same rule in a different way. It keeps the raw text the user typed in state, because '12.' is a valid thing to be halfway through typing and must not be rewritten to 12. It converts to numbers only when deriving the other field.
Pitfall 4: calling a handler instead of passing it
// Bug: runs during render, sets state, triggers another render, and so on.
<button onClick={setActiveIndex(1)}>Show</button>
// Fix: pass a function that React calls later.
<button onClick={() => setActiveIndex(1)}>Show</button>The same mistake appears when passing callbacks down: onShow={handleShow()} passes the return value of handleShow (usually undefined) instead of the function. When a lifted handler needs an argument, wrap it in an arrow function at the call site.
Pitfall 5: mutating lifted state
When state lives in a parent, many children can read the same object or array, so mutation causes more confusing bugs. React compares the new state with the old one by reference. If you change the array in place and pass the same array to the setter, React sees no change and skips the render.
import { useState } from 'react';
function TodoItem({ todo, onToggle }) {
return (
<li>
<label>
<input
type="checkbox"
checked={todo.done}
onChange={() => onToggle(todo.id)}
/>
{todo.text}
</label>
</li>
);
}
export default function TodoApp() {
const [todos, setTodos] = useState([
{ id: 1, text: 'Write chapter', done: false },
{ id: 2, text: 'Review chapter', done: false },
]);
function toggle(id) {
// Bug: todos.find(t => t.id === id).done = true; setTodos(todos);
setTodos(prev =>
prev.map(t => (t.id === id ? { ...t, done: !t.done } : t))
);
}
const remaining = todos.filter(t => !t.done).length;
return (
<>
<ul>
{todos.map(t => (
<TodoItem key={t.id} todo={t} onToggle={toggle} />
))}
</ul>
<p>{remaining} remaining</p>
</>
);
}map returns a new array and { ...t } returns a new object for the changed item, so React sees the change. The updater form prev => ... also avoids stale values if the handler runs several times before a render. Notice that remaining is derived during render rather than stored, which applies the previous chapter's rule again.
Pitfall 6: lifting too far, or not far enough
Lifting has a correct stopping point, which is the closest common parent of the components that need the value.
- Lifted too high: If state lives in
Appbut only one panel uses it, every keystroke re-renders the whole tree and every component in between must carry props it does not use. Push the state back down to the component that needs it. - Lifted to the wrong place: If two siblings share state but it lives in one of them, the other cannot reach it. Props only flow down, so the owner must be an ancestor of every component that reads or writes the value.
- Lifted twice: Two parents each keep a copy of the same value. Pick one owner and delete the other copy.
A debugging routine
When a lifted value misbehaves, check these in order.
Two tools help you follow this path.
- React DevTools. Open the Components tab, select the suspected owner, and read its hooks. Then select a child and compare its props. If the parent's state is right and the child's props are wrong, the bug is in how you pass them. If a child shows its own
Stateentry for something that should be shared, you have found a duplicate. - Logging at the owner. Add
console.log('render', text)in the parent and a log inside the change handler. If the handler logs but the render does not, the setter received the same reference, which points to mutation. If neither logs, the event handler is not wired up.
Exercises
Exercise
A Field child declares const [text, setText] = useState(props.value). The parent's Reset button sets its own state to '', but the field still shows the old text. Explain why, and give the fix.
Show answer
useState uses its argument only on the first render, so later changes to props.value are ignored. The child holds its own copy that the parent cannot change. Remove the child's state and use props.value as the input's value, and call props.onChange in the handler. The parent is then the only owner.
Exercise
A parent holds const [qty, setQty] = useState(1) and renders <input type="number" value={qty} onChange={e => setQty(e.target.value)} />. The total is calculated with qty + 1. After typing 2, the total shows 21. What went wrong, and how do you fix it?
Show answer
e.target.value is always a string, so qty becomes '2' and '2' + 1 concatenates to '21'. Convert in the handler with setQty(Number(e.target.value)). Alternatively, store the raw text and convert to a number when deriving the total. Handle an empty input as well, because Number('') is 0.
Exercise
You mutate a lifted array with todos.push(newTodo); setTodos(todos);. The list does not update. Write the corrected setter call.
Show answer
setTodos(prev => [...prev, newTodo]); This creates a new array, so React sees a changed reference and re-renders. The updater form also keeps the result correct if several updates are queued before the next render.