4

splice() mutates the original array and should be avoided. Instead, one good option is to use filter() which creates a new array so does not mutates the state. But I used to remove items from an array using splice() with spread operator.

removeItem = index => {
  const items = [...this.state.items];
  items.splice(index, 1);

  this.setState({ items });
}

So in this case when I log items changes but this.state.items stays unchanged. Question is, why does everyone use filter instead of splice with spread? Does it have any cons?

Yusufbek
  • 2,180
  • 1
  • 17
  • 23

2 Answers2

1

filter() has a more functional approach, which has its benefits. Working with immutable data is much more easier, concurrency and error safe.

But in your example, you are doing something similar by creating the items array. So you are still not mutating any existing arrays.


const items = [...this.state.items];

Creates a copy of this.state.items, thus it will not mutate them once you do a splice().

So considering you approach, it is no different than filter(), so now it just boils down to a matter of taste.

const items = [...this.state.items];
items.splice(index, 1);

VS

this.state.items.filter(i => ...);

Also performance may be taken into consideration. Check this test for example.

Horatiu Jeflea
  • 7,256
  • 6
  • 38
  • 67
  • Check this test too please https://www.measurethat.net/Benchmarks/Show/814/0/remove-by-splice-vs-copywithin-vs-filter – Yusufbek Oct 12 '19 at 08:04
  • Yes, depends on what is your environment, your tests and so on. But I wouldn't worry about this as it runs in the browser. If it was a server call which handles hundreds of requests per second, then I would consider performance a priority, otherwise not. Use most maintainable code. – Horatiu Jeflea Oct 12 '19 at 08:04
0
 const items = [...this.state.items]; // spread
 const mutatedItems = this.state.items.filter(() => {}) // filter

they are the same.
although i found spread line is confusing, and less intuitive than filter.

but i prefer destructuring:

 const { items } = this.state // destructure
 item.splice()

why? because sometimes within a function/method i have other destructuring assignment such

  const { modalVisible, user } = this.state

So i think why not destructure item as well there. For some who writes a lot of codes in multiple codebase, it would help a lot to work on on "how accurate, and fast can this code skimmed?" as i myself dont really remember what i wrote last week.
While using spread would make me write more lines and doesnt help me when re-read it next month.

Nikko Khresna
  • 1,024
  • 8
  • 10