Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 4.7 — Updating Arrays in State
React · Example 3 of 3

Arrays of objects: copy the item you change

The bad button ticked Big Bellies in my list only, yet it shows as seen in both lists. The bad toggle copied the array but mutated an object both lists share. The good toggle made a new object for the one item, so only your list got Lunar Landscape.

Arrays in state are read-only too: add, remove, replace, insert, reorder and sort by building a new array with spread, filter, map, slice or the copying methods toSorted and toReversed, and copy any object inside an array before changing it.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

State todos is [{ id, text, done }]. Write the three handlers addTodo(text), toggleTodo(id) and deleteTodo(id) without mutating.

02

Write a handler that moves the item with a given id one place up in the list (do nothing if it's already first).

Explain it without notes

01

Which array methods should you avoid on state, and what do you use instead?

02

How do you insert an item at position i without mutating?

03

Why can [...list] followed by copy[0].done = true still be a mutation bug?

04

Why should list items be identified by id instead of index?

Arrays of objects: copy the item you change

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Mine: Big Bellies ✓, Lunar Landscape | Yours: Big Bellies ✓, Lunar Landscape
Mine: Big Bellies ✓, Lunar Landscape | Yours: Big Bellies ✓, Lunar Landscape ✓