Lesson 5 of 8
Don't mutate, make a copy
- 14 min
- 5 checks
- 3 hints
- Go to task
Goal
Why we freeze data
Explanation
When you change an array in place, what it used to hold is lost, and with it the answer to the simplest question there is: what changed? Undo, comparisons and change detection in every UI library are built on that question.
The alternative is for every change to produce a new value: you write [...list, item] instead of push, list.filter(x => x !== y) instead of splice, and {...obj, key: v} instead of changing the property directly.
The array here is frozen with Object.freeze, so in strict mode any attempt to change it throws an error instead of failing silently.
Your task
Make adding and removing work without mutating the array in state.items, and keep the change counter correct.
Checks
5 checks- The list starts with three items
- Adding works without an error
- Removing takes away the first item
- Adding creates a new array instead of changing the old one
- The change counter goes up with every action