Updating Arrays in State

Add to and change a todo list without mutating it: [...array, item] to add, map to change one item.

React · beginner · 8 min · 28 steps · free

What you'll learn

StateArrays.jsx

import { useState } from 'react';

let nextId = 3;

export default function TodoList() {
  const [todos, setTodos] = useState([
    { id: 1, text: 'Learn JSX', done: true },
    { id: 2, text: 'Learn state', done: false },
  ]);

  function addTodo() {
    setTodos([...todos, { id: nextId++, text: 'Learn effects', done: false }]);
  }

  function toggle(id) {
    setTodos(todos.map((t) => (t.id === id ? { ...t, done: !t.done } : t)));
  }

  return (
    <div>
      <ul>
        {todos.map((t) => (
          <li key={t.id}>
            <input type="checkbox" checked={t.done} onChange={() => toggle(t.id)} />
            {t.text}
          </li>
        ))}
      </ul>
      <button onClick={addTodo}>Add</button>
    </div>
  );
}

Step by step

  1. React renders <TodoList> for the first time: it calls the TodoList function.
  2. useState runs for the first time, so React stores the starting value for todos and returns it: [{ id: 1, text: "Learn JSX", done: true }, { id: 2, text: …].
  3. map turns each todo into an <li> with a checkbox; key={t.id} keeps each row matched to its todo.
  4. For t = { id: 2, text: "Learn state", done: false }, the callback returns <li>…</li>.
  5. TodoList returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.
  6. React turns the JSX into real page elements and shows them: look at the Screen panel.
  7. You click the “Add” button. React calls its onClick handler.
  8. [...todos, newTodo] builds a new array: all the old items plus one more.
  9. React renders <TodoList> again (render 2): it calls TodoList once more, from the top.
  10. useState returns the value React has kept for todos: [{ id: 1, text: "Learn JSX", done: true }, { id: 2, text: …]. The starting value is only used on the first render.
  11. For t = { id: 1, text: "Learn JSX", done: true }, the callback returns <li>…</li>.
  12. For t = { id: 2, text: "Learn state", done: false }, the callback returns <li>…</li>.
  13. For t = { id: 3, text: "Learn effects", done: false }, the callback returns <li>…</li>.
  14. TodoList returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.
  15. React compares the new JSX with the last one and updates only what changed on the page.
  16. You tick "Learn state". Its onChange arrow calls toggle(2).
  17. For t = { id: 1, text: "Learn JSX", done: true }, the callback returns { id: 1, text: "Learn JSX", done: true }.
  18. For id 2, the arrow returns a copy with done flipped to true.
  19. Every other todo is returned as it was.
  20. setTodos(todos.map((t) => (t.id === id ? { ...t, done: !t.done } : t))) does not change todos right away: React queues the update and will render again. In this call todos is still [{ id: 1, text: "Learn JSX", done: true }, { id: 2, text: …].
  21. It runs toggle(t.id).
  22. React renders <TodoList> again (render 3): it calls TodoList once more, from the top.
  23. useState returns the value React has kept for todos: [{ id: 1, text: "Learn JSX", done: true }, { id: 2, text: …]. The starting value is only used on the first render.
  24. For t = { id: 1, text: "Learn JSX", done: true }, the callback returns <li>…</li>.
  25. For t = { id: 2, text: "Learn state", done: true }, the callback returns <li>…</li>.
  26. For t = { id: 3, text: "Learn effects", done: false }, the callback returns <li>…</li>.
  27. TodoList returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.
  28. "Learn state" is ticked on the page.

Common mistakes

Best practices

Key takeaways

Check yourself

Which keeps state immutable?

Answer: setList([...list, x])

Remove item 2?

Answer: list.filter(t => t.id !== 2). splice changes the array.

·

More in State and Events