-1

What is the difference between using the methods below ?

I used this to update a React Component state:

changeRate(id, rate) {
  let color = this.state.colors.find((c) => c.id == id);
  color.rating = rate;
  this.setState({ color });
}

In the book i am following, this was used:

rateColor(id, rating) {
    const colors = this.state.colors.map(color =>
    (color.id !== id) ? color : { ...color, rating })
    this.setState({colors})
}
  • And what [CertainPerformance](https://stackoverflow.com/a/64360822/1218980) is talking about in their answer: [Why can't I directly modify a component's state, really?](https://stackoverflow.com/q/37755997/1218980) – Emile Bergeron Oct 14 '20 at 21:10

1 Answers1

0

If you use the first method, you will be mutating the existing state, which can cause unpredictable behavior (such as a failure to re-render) and should never be done in React.

The second method does not mutate the existing state - you're creating an entirely new color object, which is what one should do when one needs to update state in React.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • So array.find() returns a reference to the value of the element that passes the test, not a copy of that value or element right ? – Klaidi Dingu Oct 14 '20 at 20:18
  • Right, objects / arrays are only ever copied if you do so *explicitly*, like with `JSON.stringify`/`parse`, or with `.slice`, or with spread, etc. Unless one uses one of the few specific techniques to clone an object, the object will not be cloned. – CertainPerformance Oct 14 '20 at 20:19
  • Thank you for the help! – Klaidi Dingu Oct 14 '20 at 20:22