Skip to content

QuizNot attempted

Mutating state and setting the same object

After clicking, what is rendered?
function App() {
const [obj, setObj] = useState({ a: 1 });
const handleClick = () => {
obj.a = 5;
setObj(obj);
};
return (
<div onClick={handleClick}>
{obj.a}
</div>
);
}
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • 1
  • setObj(obj) passes the same reference, and React bails out when Object.is(old, new) is true, so nothing re-renders and the DOM still shows 1 even though obj.a is 5 in memory.
  • Not 5: the mutation never triggers a render, so it never reaches the DOM (until something else re-renders).
  • Not an error: mutating state is a bug, not a thrown exception.
  • Not undefined: a still exists on the object.
  • Fix: setObj({ ...obj, a: 5 }).