Creating a copy of the original data then calling setState()?

Why do we create copies of data or objects for example:

Why do we do this and not just call setState() on the original?

Should I be doing this for every obj or data I am dealing with?

Ok so I did some googling and well I found this very nice stackoverflow answer

https://stackoverflow.com/questions/37755997/why-cant-i-directly-modify-a-components-state-really

The second answer is the best explanation.

If anyone has any other input, I’d still love to hear it!

2 Likes

Should I be doing this for every obj or data I am dealing with?

You should create a copy of anything in the state that you are going to change. In your example, I assume counters is a property in the component’s state. In this case, you would need to copy both the counters array and the counter object because both of those objects are changed in the code you provided. The counters array is changed when you’re inserting a new object. When you make a copy of the counters array, you have a new array but it still points to all the original objects. Since you want to also decrement the value of the counter object, you need to make a copy of that as well.

1 Like

In simple words because updating the state is more than just set the new values to your current state, there are other ‘jobs’ that must be done and setState will do that for you under the hood, otherwise you would have to do yourself.

React Docs > setState

2 Likes