JacopoStanchi
JacopoStanchi

Reputation: 2146

Does shallow copy of the state create errors?

Updating a state property without copying it and using setState() can lead to errors as stated by this article. What I want to know is that if I have a list of objects in the state like so:

this.state = {
  myList: [
    {name: "Nestor"},
    {name: "Rufus"}
  ]
};

Would it cause errors if I just update it with a shallow copy like that:

let list = [...this.state.myList];
//I modify the list here
this.setState({myList: list});

Or I have to do a deep copy to be absolutely certain that there won't be bugs?

let list = JSON.parse(JSON.stringify(this.state.myList));
//I modify the list here
this.setState({myList: list});

Thank you for your help.

Upvotes: 0

Views: 135

Answers (1)

Utsav Patel
Utsav Patel

Reputation: 2889

It depends on your use case.

Most of the time you can get away with a shallow copy.

But if for some reason, the props (or state) you are passing needs deep comparison, then you will have to resort to libraries like react-fast-compare.

Using a shallow copy won't introduce any bugs, at worst some of your components will not re-render properly.

You might want to read these :

https://daveceddia.com/react-redux-immutability-guide/

https://github.com/FormidableLabs/react-fast-compare

Upvotes: 1

Related Questions