Updating Objects in State

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

What you'll learn

StateObjects.jsx

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

Step by step

  1. React renders <Profile> for the first time: it calls the Profile function.
  2. useState runs for the first time, so React stores the starting value for person and returns it: { name: "Ada", city: "London" }.
  3. Profile returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.
  4. React turns the JSX into real page elements and shows them: look at the Screen panel.
  5. You click the “Move to Paris” button. React calls its onClick handler.
  6. { ...person, city: "Paris" } makes a new object: a copy of person with city replaced. person itself is not touched.
  7. setPerson(updated) hands React the new object. It is a different object from the old one, so React will render again.
  8. React renders <Profile> again (render 2): it calls Profile once more, from the top.
  9. useState returns the value React has kept for person: { name: "Ada", city: "Paris" }. The starting value is only used on the first render.
  10. Profile returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.
  11. The page says Paris. Try the bug version to see what happens when the object is changed in place.

Common mistakes

Best practices

Key takeaways

Check yourself

{ ...a, x: 1 } creates?

Answer: A new object

Why did the bug version not update?

Answer: setPerson got the same object. Object.is(old, new) was true.

·

More in State and Events