Sub topic 13
Common pitfalls and how to debug them
This chapter assumes you know useState, props, and passing callbacks to children. It covers the mistakes people make most often after they lift state, and how to find them.
Pitfall 1: Duplicated state
The most common error is copying a prop into state. The copy is made once, on the first render, and never updates after that.
import { useState } from 'react';
function Field({ value, onChange }) {
// Bug: the prop is copied once, so later changes to `value` are ignored.
const [text, setText] = useState(value);
return (
<input
value={text}
onChange={e => {
setText(e.target.value);
onChange(e.target.value);
}}
/>
);
}
export default function App() {
const [name, setName] = useState('Ada');
return (
<>
<Field value={name} onChange={setName} />
<button onClick={() => setName('Grace')}>Reset to Grace</button>
<p>Parent says: {name}</p>
</>
);
}Click the button. The paragraph shows "Grace", but the input still shows "Ada". There are now two sources of truth again.
The fix is to delete the local state and read the prop directly. The parent already owns the value.
function Field({ value, onChange }) {
return <input value={value} onChange={e => onChange(e.target.value)} />;
}Pitfall 2: Storing what you can compute
If one value can be calculated from another, do not store both. In the temperature converter, the Fahrenheit value is derived from the Celsius value during render. Storing both means you must update both on every change, and sooner or later one update is forgotten.
Ask this question for each piece of state: can I calculate it from props or from other state? If yes, calculate it.
Pitfall 3: Mismatched value types
An input's event.target.value is always a string. If the parent stores a number, the types drift apart.
// Bug: the parent expects a number but receives a string such as "42".
<input value={age} onChange={e => setAge(e.target.value)} />Later, age + 1 gives "421" instead of 43. Convert once, at the boundary where the value enters state, and decide whether the state holds the raw text or a parsed number. For editable fields, keeping the raw string is safer, because a half-typed value such as "3." would otherwise be lost. Parse during render when you need a number.
Pitfall 4: Calling the callback instead of passing it
// Bug: runs setActiveIndex during render, causing a render loop.
<button onClick={setActiveIndex(1)}>Show</button>
// Correct: pass a function that React calls on click.
<button onClick={() => setActiveIndex(1)}>Show</button>If React reports "Too many re-renders", look for a call like this.
Pitfall 5: Over-lifting
Lifting state higher than necessary makes more components re-render and forces you to pass more props. Place state in the closest common parent of the components that need it, and no higher. If only one component uses a value after a refactor, move it back down.
A debugging checklist
When two components disagree, work through these steps in order.
- Find every place the value is stored. Search for
useStatecalls that hold the same information. There should be exactly one. - Check that each child receives both the value and the callback, and that the names match on both sides.
- Log the value in the owner and in the child during render. If they differ, the child is using a copy.
- Check types with
typeof. A number and a string that look the same behave differently. - Open React DevTools and select the owner component. Its hooks panel shows the current state, and the children show their props.
Exercise
A child component has const [count, setCount] = useState(props.count). The parent changes count to 10, but the child still shows 0. What is wrong, and how do you fix it?
Show answer
The child copied the prop into its own state on the first render, so it has a second source of truth that ignores later prop changes. Remove the child's state and read props.count directly. If the child must change it, call a callback prop so the parent updates the value.
Exercise
An input is wired as onChange={e => setQuantity(e.target.value)} and the parent computes quantity + 1. Typing 5 gives 51. Why, and what are two fixes?
Show answer
e.target.value is a string, so + concatenates. Either store the string and parse it with Number(quantity) when you compute, or convert before storing with setQuantity(Number(e.target.value)). Keeping the string is better for fields where the user can type partial input.