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);
}

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.

Further reading

Problem with a question

React · Junior · question 14

Test yourself

Take the React · Junior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz