2

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?

albert
  • 1,158
  • 3
  • 15
  • 35
  • 1
    Since you can't manipulate a state directly, you always end up with either setting a completely new value you to your state store, or copying the existing value and populating it with something new. Therefore it's totally finde – noa-dev Sep 26 '18 at 05:35

1 Answers1

0

For this example it is really not an issue, you might want to be more specific on complex objects but not on a simple array :)

As long as it works its fine :P You can read a few discussions on the topic on stack as well as check the docs, most discussions relate to more substantial states:

ES6 React - What are the difference between reference, shallow copy and deep copy and how to compare them?

Tom Rowe
  • 449
  • 2
  • 10