Skip to content

Updating Arrays in State

The Course
•
20 min study

When a list lives in state, you change it by giving setTopics a new array. React compares the old state with the new one. If you hand back the same array, even with different contents, React sees nothing new and skips the re-render.

Add, remove, toggle 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"; const ideas = ["Effects", "Forms", "Custom hooks", "Context"]; export default function App() { const [topics, setTopics] = useState([ { id: 1, title: "Props", done: true }, { id: 2, title: "State", done: false }, ]); function addTopic() { const title = ideas[topics.length % ideas.length]; setTopics([...topics, { id: Date.now(), title, done: false }]); } function removeTopic(id) { setTopics(topics.filter((topic) => topic.id !== id)); } function toggleTopic(id) { setTopics(topics.map((topic) => topic.id === id ? { ...topic, done: !topic.done } : topic )); } return ( <main> <h1>Topics</h1> <ul> {topics.map((topic) => ( <li key={topic.id}> <label> <input type="checkbox" checked={topic.done} onChange={() => toggleTopic(topic.id)} />{" "} {topic.title} </label>{" "} <button onClick={() => removeTopic(topic.id)} aria-label={`Remove ${topic.title}`}>Remove</button> </li> ))} </ul> <button onClick={addTopic}>Add a topic</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.

Try all three buttons, then read how each handler builds its new array.

Add: spread into a new array

JavaScript
setTopics([...topics, { id: Date.now(), title, done: false }]);

[...topics, x] makes a new array with every old item, then x. To add at the start, write [x, ...topics]. This small lab creates an id in the add handler with Date.now(), the current time in milliseconds.

A timestamp is a shortcut for these manual clicks, not a guarantee of a unique id: two items created in the same millisecond can collide. In an application, use an id from the server, crypto.randomUUID(), or a counter owned by the code creating the items. Create it once when adding the item, never in map.

Remove: filter

JavaScript
setTopics(topics.filter((topic) => topic.id !== id));

filter keeps every topic except the one with this id, in a new array.

Change one item: map

JavaScript
setTopics(topics.map((topic) =>
  topic.id === id ? { ...topic, done: !topic.done } : topic
));

Every topic is copied into the new array as it is, except the one being changed. That one is replaced by a new object: { ...topic, done: ... } copies its fields and overrides done.

Predict: push

Replace addTopic's setTopics line with the version many people try first:

JavaScript
topics.push({ id: Date.now(), title, done: false });
setTopics(topics);

Click Add a topic once. What do you see? Now tick a checkbox. What do you see now?

Check your prediction

The click seems to do nothing. push changed the existing array, and setTopics received that same array, so React saw nothing new and didn't re-render.

Ticking a checkbox then shows the new topic suddenly appearing. The toggle made a new array with map, and that new array included the item push had slipped into the old one. Bugs like this, where something appears late, are a sign that state was changed in place.

The rule: never change state directly. push, pop, splice, sort and reverse all change an array in place. Use [...a, x], filter, map, or copy first with [...a].sort().

Put the spread version back.

Passing a handler to a child

Later you'll want each row in its own component, like TaskRow in the last lesson. The row can't change topics itself: that state belongs to App. So App passes the row a function to call, as a prop:

JSX
<TopicRow topic={topic} onRemove={removeTopic} />
JSX
function TopicRow({ topic, onRemove }) {
  return (
    <li>
      {topic.title} <button onClick={() => onRemove(topic.id)}>Remove</button>
    </li>
  );
}

The row says what happened; App decides what to do about it. Day 5 builds on this pattern.

Your turn

Exercise

Clear finished topics

Add a Clear finished button that removes every topic whose done is true. Disable it when nothing is finished.

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"; const ideas = ["Effects", "Forms", "Custom hooks", "Context"]; export default function App() { const [topics, setTopics] = useState([ { id: 1, title: "Props", done: true }, { id: 2, title: "State", done: false }, ]); function addTopic() { const title = ideas[topics.length % ideas.length]; setTopics([...topics, { id: Date.now(), title, done: false }]); } function removeTopic(id) { setTopics(topics.filter((topic) => topic.id !== id)); } function toggleTopic(id) { setTopics(topics.map((topic) => topic.id === id ? { ...topic, done: !topic.done } : topic )); } return ( <main> <h1>Topics</h1> <ul> {topics.map((topic) => ( <li key={topic.id}> <label> <input type="checkbox" checked={topic.done} onChange={() => toggleTopic(topic.id)} />{" "} {topic.title} </label>{" "} <button onClick={() => removeTopic(topic.id)} aria-label={`Remove ${topic.title}`}>Remove</button> </li> ))} </ul> <button onClick={addTopic}>Add a topic</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

Removing several items is still a filter: keep the topics that aren't done.

Hint 2: a first step

topics.some((topic) => topic.done) is true when at least one is done.

Show one solution
JSX
<button
  onClick={() => setTopics(topics.filter((topic) => !topic.done))}
  disabled={!topics.some((topic) => topic.done)}
>
  Clear finished
</button>

Was this article helpful?

Your response is saved on this device.