The ability to reply to discussions is limited to PRO members. Want to join in the discussion? Click here to subscribe now.

Redux: Avoiding Array Mutations with concat(), slice(), and ...spread

Redux: Avoiding Array Mutations with concat(), slice(), and ...spread

3:54
Learn how to avoid mutating arrays using concat(), slice(), and the ES6 array spread operator.
Watch this lesson now
Avatar
egghead.io

Learn how to avoid mutating arrays using concat(), slice(), and the ES6 array spread operator.

Avatar
raarts

Why not just make a copy of the state array, modify the copy, and return that?

In reply to egghead.io
Avatar
Sequoia McDowell

Is there a library of non-mutative array methods? Rewriting versions of Array.prototype.splice over and over to avoid mutation seems a bit crazy. :p

Avatar
Dan Abramov

This is exactly what slice() does. As long as you don’t mutate the original array there is no difference.

In reply to raarts
Avatar
Simon

Going through the videos again to consolidate my now growing redux skills :)

For the removeCounter() reducer, I used array.filter() instead of slice. I am pretty sure this is okay too - since it doesn't directly mutate listBefore. Just checking this is another valid way of updating the state?

Any downsides of using this when the array becomes much bigger?

const removeCounter = (list, index) => {
  return list.filter((item, i) => {
    return i !== index
  })
}
In reply to Dan Abramov
HEY, QUICK QUESTION!
Joel's Head
Why are we asking?