Make a new object with ...spread instead of changing the old one. The bug version shows why changing it in place leaves the screen stuck.
React · beginner · 7 min · 11 steps · free
import { useState } from 'react';
export default function Profile() {
const [person, setPerson] = useState({ name: 'Ada', city: 'London' });
function moveToParis() {
const updated = { ...person, city: 'Paris' };
setPerson(updated);
}
return (
<div>
<p>{person.name} lives in {person.city}.</p>
<button onClick={moveToParis}>Move to Paris</button>
</div>
);
}<Profile> for the first time: it calls the Profile function.useState runs for the first time, so React stores the starting value for person and returns it: { name: "Ada", city: "London" }.Profile returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.onClick handler.{ ...person, city: "Paris" } makes a new object: a copy of person with city replaced. person itself is not touched.setPerson(updated) hands React the new object. It is a different object from the old one, so React will render again.<Profile> again (render 2): it calls Profile once more, from the top.useState returns the value React has kept for person: { name: "Ada", city: "Paris" }. The starting value is only used on the first render.Profile returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.Answer: A new object
Answer: setPerson got the same object. Object.is(old, new) was true.
← Update Functions · Updating Arrays in State →