albert
albert

Reputation: 1348

Is it safe to make a shallow copy of React state array, and modify that shallow copy?

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?

Upvotes: 2

Views: 3159

Answers (1)

Tom Rowe
Tom Rowe

Reputation: 479

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?

Upvotes: 0

Related Questions