Destructuring, Spread, and Rest
Pulling values out of objects and arrays, and copying them without mutation.
What you'll learn
- Destructuring objects and arrays, with defaults and renaming
- The difference between rest (collecting) and spread (expanding)
- How to update data by copying instead of mutating
- Why "copying instead of mutating" is a hard requirement in React
Destructuring objects
Destructuring unpacks properties into variables in one step. It is the reason React props read the way they do.
The default only applies when the property is undefined — not when it is
null, 0, or an empty string. That distinction catches people out.
Destructuring in parameters
You can destructure directly in a parameter list. This is how almost every React component receives its props:
Destructuring arrays
Arrays destructure by position rather than name, so you choose the names:
This is exactly the shape of const [count, setCount] = useState(0) — useState
returns a two-element array, and you name both parts at the call site.
Rest and spread
They look identical — three dots — but they work in opposite directions.
Rest collects the leftovers into a new variable. It goes on the left of an assignment, or last in a parameter list:
Spread expands a value into somewhere else. It goes on the right:
Note that base is untouched. That is the whole point.
Copying instead of mutating
This is the habit the rest of the course depends on. React decides whether to re-render by comparing values by identity: if you mutate an object in place, it is still the same object, and React sees no change.
The same applies to arrays. Reach for the methods that return a new array
(map, filter, concat, spread) rather than the ones that change it in place
(push, splice, sort, reverse):
One level deep
Spread makes a shallow copy. Nested objects are still shared, so updating a nested value means copying at each level you change:
Common mistakes
- Expecting a default to fill in
null. Defaults only apply toundefined. - Confusing rest with spread. Left side collects, right side expands.
- Trusting a shallow copy.
{ ...user }shares every nested object. - Sorting without copying.
sortandreversechange the array in place.
Exercise
addTag currently mutates the post it is given, so original changes too.
Rewrite it to return a new post with the tag appended, leaving original
untouched. Both logged tag lists should differ when you are done.