dspjm
dspjm

Reputation: 5850

Reactjs: Is it necessary to copy object in component state before modifying it?

Suppose my my reactjs component has two states:

a: {
    a: 1
},
b: [1, 2, 3]

Now I want them to become:

a: {
    a: 1,
    b: true
},
b: [1, 2, 3, 4]

Is it correct to do it by:

this.state.a.b = true;
b = this.state.b.push(4);
this.setState({
    a: this.state.a,
    b: b
});

If not, what is the appropriate way to do it.

Upvotes: 2

Views: 1280

Answers (3)

Isaac Pak
Isaac Pak

Reputation: 4961

Straight from the docs:

Do Not Modify State Directly

For example, this will not re-render a component:

// Wrong
this.state.comment = 'Hello';

Instead, use setState():

// Correct
this.setState({comment: 'Hello'});


So it is not necessary to copy an object before modifying it, if you use setState

So your code might look like this:

this.setState({
    a: (this.state.a.b = true),
    b: this.state.b.push(4)
})

Upvotes: 0

Jackie Huang
Jackie Huang

Reputation: 145

Best way to do it.

  this.setState({
    a: Object.assign({}, this.state.a, { b: true }),
    b: [...this.state.b, 4]
  });

Upvotes: 2

Ori Drori
Ori Drori

Reputation: 192016

The state properties should be replaced, and not mutated:

this.setState({
    a: { // create new a object
        a: this.state.a.a,
        b: true
    },
    b: this.state.b.concat([4]) // create new b array
});

Upvotes: 0

Related Questions