When does calling a state setter cause a re-render?
React re-renders when the new state is different from the current one, compared with Object.is. Setting the same primitive value, or the very same object reference, usually skips the render. A new object with equal contents counts as different.
Explain it simply
State is like the scoreboard at a cricket ground. If the scorer writes the same score again, nobody needs to look up. If the number changes, the crowd checks the board.
React compares the old and new value with Object.is. For numbers and strings that means value equality. For objects and arrays it compares the reference, so a new array with the same items looks like a change.
Example
function Demo() {
const [n, setN] = useState(5);
const [list, setList] = useState([1]);
return (
<>
<button onClick={() => setN(5)}>same number</button> {/* no re-render */}
<button onClick={() => setList([...list])}>copy</button> {/* re-renders */}
<button onClick={() => list.push(2)}>mutate</button> {/* no re-render, UI stale */}
</>
);
}What to say in the interview
"A setter schedules a re-render only if the new value differs from the current one by Object.is. For objects and arrays I always create a new copy, because mutating the existing one keeps the same reference and React will not notice. When the value is the same, React may still call the component once more but will bail out of the children."
Common mistakes
- Mutating state with push or direct assignment and wondering why the screen does not update.