Skip to content

Updating Objects in State

The Course
•
15 min study

Objects in state follow the same rule as arrays: make a new one instead of changing the old one. The spread syntax { ...old } copies every field, and any field written after it overrides the copy.

Settings in one object React · 3 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useState } from "react"; export default function App() { const [settings, setSettings] = useState({ name: "Ada", dailyGoal: 30, reminders: false, }); function raiseGoal() { setSettings({ ...settings, dailyGoal: settings.dailyGoal + 10 }); } function toggleReminders() { setSettings({ ...settings, reminders: !settings.reminders }); } return ( <main> <h1>{settings.name}'s settings</h1> <p>Daily goal: {settings.dailyGoal} minutes</p> <p>Reminders: {settings.reminders ? "on" : "off"}</p> <button onClick={raiseGoal}>Raise goal by 10</button>{" "} <button onClick={toggleReminders}>Turn reminders {settings.reminders ? "off" : "on"}</button> </main> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } main { max-width: 32rem; margin: 1.5rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.75rem; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } .card h2 { margin: 0 0 0.25rem; font-size: 1.1rem; } .muted { color: #6b7785; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
JavaScript
setSettings({ ...settings, dailyGoal: settings.dailyGoal + 10 });

This new object has the same name and reminders as before, and a new dailyGoal. Order matters: fields after ...settings override it. Written the other way round, { dailyGoal: 40, ...settings }, the old dailyGoal from the spread would win.

Predict: changing the object directly

Replace raiseGoal with:

JavaScript
function raiseGoal() {
  settings.dailyGoal = settings.dailyGoal + 10;
  setSettings(settings);
}

Click Raise goal by 10 twice, then Turn reminders on. What does the page show after each click?

Check your prediction

The goal stays at 30 for both clicks: it's the same object, so React skips the re-render. Then Turn reminders on jumps the goal to 50: the toggle makes a new object with the spread, which copies the dailyGoal you'd changed in place. It's the same late-appearing bug as push in the last lesson.

Put the spread version back.

Nested objects

The spread copies one level. If settings held an object, such as settings.theme = { colour: "teal", size: "large" }, changing the colour needs a copy at each level:

JavaScript
setSettings({
  ...settings,
  theme: { ...settings.theme, colour: "navy" },
});

If you find yourself writing deep copies often, the state may be too nested. Flatter state, or a few separate useState calls, is easier to update.

Your turn

Exercise

Text size, two levels down

The worked example above changes a field one level down. This one goes deeper. Add a theme whose font is an object too, to the starting value in useState:

JavaScript
theme: { colour: "teal", font: { family: "serif", size: 16 } },

Show it under the reminders as Theme: teal, serif 16px. Then add a button Bigger text that adds 2 to the font size and keeps everything else as it is: the colour, the font family, and the other settings. Check it: click Raise goal by 10, then Bigger text twice. The page should show:

Text
Daily goal: 40 minutes
Theme: teal, serif 20px
Your working space React · 3 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useState } from "react"; export default function App() { const [settings, setSettings] = useState({ name: "Ada", dailyGoal: 30, reminders: false, }); function raiseGoal() { setSettings({ ...settings, dailyGoal: settings.dailyGoal + 10 }); } function toggleReminders() { setSettings({ ...settings, reminders: !settings.reminders }); } return ( <main> <h1>{settings.name}'s settings</h1> <p>Daily goal: {settings.dailyGoal} minutes</p> <p>Reminders: {settings.reminders ? "on" : "off"}</p> <button onClick={raiseGoal}>Raise goal by 10</button>{" "} <button onClick={toggleReminders}>Turn reminders {settings.reminders ? "off" : "on"}</button> </main> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } main { max-width: 32rem; margin: 1.5rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.75rem; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } .card h2 { margin: 0 0 0.25rem; font-size: 1.1rem; } .muted { color: #6b7785; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea

Write out the path to the value that changes: settings.theme.font.size. Every object on that path changes, because something inside it changes, so each one needs its own new copy. Each copy also has to keep the fields you aren't changing. How many objects is that here, compared with the worked example?

Hint 2: a first step

Build the copies from the outside in, and check after each one. Start with the outer copy of settings and a new theme that has only a font with the new size, then click Bigger text. The line loses the colour and the family, because your new objects only have the one field you wrote. Each object that lost something needs a spread of the object it replaces.

Show one solution
JavaScript
const [settings, setSettings] = useState({
  name: "Ada",
  dailyGoal: 30,
  reminders: false,
  theme: { colour: "teal", font: { family: "serif", size: 16 } },
});

function growText() {
  setSettings({
    ...settings,
    theme: {
      ...settings.theme,
      font: { ...settings.theme.font, size: settings.theme.font.size + 2 },
    },
  });
}
JSX
<p>
  Theme: {settings.theme.colour}, {settings.theme.font.family} {settings.theme.font.size}px
</p>
JSX
<button onClick={growText}>Bigger text</button>

Three objects are on the path, so there are three spreads. The outer one keeps the name, goal and reminders; the middle one keeps the colour; the inner one keeps the font family. Leave out any one and the fields at that level disappear. This is also why deep nesting gets tiring: if updates like this become common, a flatter shape, such as a separate font state, is easier to change.

Was this article helpful?

Your response is saved on this device.