Chapter 8 ยท Adding Interactivity
Objects & Arrays in State
To update an object or array in state, you don't change it: you create a new copy with the changes and set that.
- What "mutation" is, and why React needs you to avoid it
- How to copy and update objects with the spread syntax
... - How to update nested objects
- How to add, remove, change, insert and sort array items without mutating
The golden rule: treat state as read-only
Numbers and strings can't be changed in place anyway: you always replace them (setX(5)). Objects and arrays can be changed in place. That's called mutation:
React decides whether to re-render by checking whether you gave it a new object. If you mutate the old one and pass it back, React sees "same object as before" and may skip the update. Mutation also breaks the "snapshot" idea from Chapter 7, because old renders would see the changed data.
The fix: create a new object and pass it to the setter.
Updating objects
Copying with spread ...
Usually you want to change one field and keep the rest. The spread syntax copies all the fields of an object:
name, and use a computed property name [e.target.name]:
Nested objects
Spread only copies one level deep. For nested data, copy each level you change:
use-immer). It lets you write code that looks like mutation (draft.artwork.city = 'Lagos') and makes the copies for you.
Updating arrays
Arrays in state are read-only too. Avoid methods that mutate, and use methods that return a new array:
| Task | ๐ด Avoid (mutates) | โ Prefer (new array) |
|---|---|---|
| Add | push, unshift | [...arr, item], [item, ...arr] |
| Remove | pop, shift, splice | filter, slice |
| Change items | arr[i] = x | map |
| Sort / reverse | sort, reverse | toSorted, toReversed, or copy first |
Adding
Removing
filter keeps the items for which the test returns true:
Changing one item
map builds a new array. Return a changed copy for the item you want, and the item unchanged for the rest:
map example above.
Inserting at a position
Sorting and reversing
More examples
Example 1: a shopping cart (add, increase, decrease, remove)
Example 2: selecting several items (an array of IDs)
Example 3: moving an item up
Changing the copy is fine. It's a new array that nobody else has seen yet.
Example 4: an object containing an array
Recap
- Treat objects and arrays in state as read-only. Make a new one and set it.
- Objects:
{ ...obj, field: newValue }. Copy each nested level you change. - Arrays: add with
[...arr, x], remove withfilter, change withmap, insert withslice, sort withtoSorted. - Spread is shallow. When you change an item inside an array, copy that item too.
- For deeply nested state, consider Immer or flattening it.
Exercises
1. A complete todo list
Build a todo app: an input plus an "Add" button, a list where clicking an item toggles it as done (crossed out), and a "Delete" button on each item.
Show solution
2. Fix the mutation
Show solution
3. A profile form with one handler ๐ข easy
Keep { name, email, city } in one state object. Use a single handleChange for all three inputs.
Show solution
4. Tags without duplicates ๐ข easy
An input plus an "Add tag" button adds to a tags array, but ignores tags that are already there.
Show solution
5. Remove by id ๐ข easy
Render a list of contacts, each with a โ button that removes it.
Show solution
6. Mark all as done ๐ข easy
Add a "Mark all done" button to your todo list (Exercise 1), and a "Clear completed" button.
Show solution
Note the ({ ... }): to return an object from an arrow function, wrap it in parentheses.
7. Nested update ๐ก medium
The state is { name: 'Asha', address: { city: 'Pune', pin: '411001' } }. Make inputs that edit city and pin without losing the other fields.
Show solution
8. Insert at the top ๐ก medium
Make a "News feed" where new posts appear at the top of the list, and a "Pin" button that moves a post to the top.
Show solution
9. Sort buttons ๐ก medium
Show a list of students ({ id, name, marks }) with buttons for "Sort by name" and "Sort by marks (high โ low)". The original array must not be mutated.
Show solution
Even better: keep the original list and store only sortBy in state, then sort while rendering. That's the "don't store derived data" idea from Chapter 9.
10. A mini Kanban board ๐ด hard
Tasks have a status of 'todo', 'doing' or 'done'. Show three columns with a count in each heading. Each task gets "โ" and "โ" buttons that move it to the previous or next column.
Show solution
๐ Official docs: Updating Objects in State ยท Updating Arrays in State