For some time now I've been making adjustments to shallow copies of my states that are arrays in React and then setting state, like so.
...
this.state = {
"exampleArr": [1]
}
...
someFunction(){
let copyArr = this.state.exampleArr;
copyArr.push(2);
this.setState({
"exampleArr": copyArr
});
}
I know that in the React docs, they say to treat state as if it were immutable, and to only use setState() to change it. For a while I thought the way I was doing it was correct, since it worked and there were no problems. However, it recently occurred to me all I was doing was making a shallow copy of the state, and adjusting the shallow copy, which technically affects the original state as well.
Is what I'm doing wrong/dangerous? Should I instead, for example, make a deep copy of the array everytime I need to adjust it, like so:
...
someFunction(){
let copyArr = this.state.exampleArr.map(x => x);
copyArr.push(2);
this.setState({
"exampleArr": copyArr
});
}
Or does it not really matter for React states that are arrays?