1

I am learning React and in one of the answer, I have seen the splice method is being used while deleting an item from the array. Link to the solution : Delete item from state array in react

To remove an element from an array, just do:

array.splice(index, 1); In your case:

removePeople(e) {
  var array = [...this.state.people]; // make a separate copy of the array
  var index = array.indexOf(e.target.value)
  if (index !== -1) {
    array.splice(index, 1);
    this.setState({people: array});
  }
},

Expected: As in many other blogs, we have used the filter method to delete the items from the list. why the answer is getting upvoted and we are not using filter method here ?

Avi
  • 72
  • 8
  • 2
    whats yr question, why use splice over filter ? – 7urkm3n Jun 22 '19 at 04:48
  • filter is better than splice, as filter does not mutate the array. As you can see in the list of answers filter method has got more up-votes but accepted answer depends on who asked the question. – tarzen chugh Jun 22 '19 at 05:02

1 Answers1

1

There are no rules such as use this method for that and that method for this. However, there are two conditions to be met to ensure that React is aware of changes to state.

  1. Use setState to update state
  2. The top level keys in the state object need to be set with new values or references. I.e. appear different on a shallow comparison.

The accepted answer you have linked meets both these requirements. The key line is,

var array = [...this.state.people]    // make a separate copy of the array

Note the comment. The orginal poster has made it clear that he is creating a new reference to the array by using the spread syntax. The splice operation he performs later on is on this new array, it does not matter what operation he performs later on, React will call the render method at least once once when the new array is set as part of state.

Why filter?

Filter filters an array by a predicate and returns a new array object with the results. In some situations, this might be more flexible and convenient to use, but it has completely different behaviour. Splice allows for the precise removal of a contiguous block of elements by index whereas filter removes all elements that do not match the predicate.

The decision to use which is upto you based on what's best for the use case. React will re-render as long as the above conditions are met.

Note: In the situation presented, filter would be the performant choice as it only loops over the array once. The splice operation requires, spread and indexOf prior to it which leads to multiple enumerations over the array.

Avin Kavish
  • 5,862
  • 1
  • 13
  • 27