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.
- Use
setState
to update state
- 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.