(Overview) Arrays are mutable in JavaScript, but you should treat them as immutable when you store them in state. Just like with objects, when you want to update an array stored in state, you need to create a new one (or make a copy of an existing one), and then set state to use the new array.
You will learn
How to add, remove, or change items in array in React state
How to update an object inside of an array
How to make array copying less repetitive with Immer
Updating arrays without mutation
Adding to an array
Removing from an array
Transforming an array
Replacing items in an array
Inserting into an array
Making other changes to an array
Updating objects inside arrays
Write concise update logic with Immer
Recap
You can put arrays into state, but you can't change them.
Instead of mutating an array, create a new version of it, and update the state to it.
You can use the [...arr, newItem] array spread syntax to create arrays with new items.
You can use filter() and map() to crate new arrays with filtered or transformed items.
You can use Immer to keep your code conside.
Updating Objects in State (revisited)
(Overview) State can hold any kind of JavaScript value, including objects. But you shouldn't change object that you hold in the React state directly. Instead, when you want to update an object, you need to create a new one (or make a copy of an existing one), and then set the state to use that copy.
You will learn
How to correctly update an object in React state
How to update a nested object without mutating it
What immutability is, and how not to break it
How to make object copying less repetivie with Immer
What's mutation?
Treat state as read-only
Copying objects with the spread syntax
Updating a nested object
Write concise update logic iwth Immer
Recap
Treat all state in React as immutable
When you store objects in state, mutating them will not trigger renders and will change the state in previous render "snapshots."
Instead of mutating an object, create a new version of it, and trigger a re-render by setting state to it.
You can use the {...obj, something: 'newValue'} object spread syntax to create copies of objects.
Spread syntax is shallow: it only copies one level deep.
To update a nested object, you need to create copies all the way up from the place you're updating.