React · Junior · Question 14 of 75
Why didn't the component re-render?
const [user, setUser] = useState({ name: "Ann" });
function rename() {
user.name = "Bob";
setUser(user);
}- 1
setUsercan't be called in event handlers - only in effects - ✓Correct answer: The object was mutated, the reference is the same -
Object.issees no change - 3Objects can't be stored in
useState- only primitive values
Explanation
React compares the new value with the old one via Object.is. It's the same object, so the update is skipped. You need to create a new object: setUser({ ...user, name: "Bob" }). Mutation also breaks optimizations like memo.