Alexander Knyazev
Alexander Knyazev

Reputation: 2892

Why my react state became not-immutable?

As I remember in past I could not update react-state manualy. Now, I don't know why, I can do it.

My case: enter image description here

and the property is changed here!It works! Why?

enter image description here

P.s: I use react16.02

Upvotes: 0

Views: 93

Answers (3)

Imran Qureshi
Imran Qureshi

Reputation: 168

the state does mutate in react. and u should be very careful that u don't override it like that or you will encounter unexpected result. it is always best to copy your state into another object, then change its properties as u like and after you are done use set state to set set your object state as copied object. you can use Object.Assign or spread operator for this. spread operator is easier when you are using Arrays.

this.state = {
  myObj : {propA: "A" , propB: "B"};
}

then at some point you want to change it

let myObj = this.state.myObj;
let copyMyObj = {...myObj};
copyMyObj.propA = "C";
this.setState({
myObj: copyMyObj
});

Upvotes: 2

illiteratewriter
illiteratewriter

Reputation: 4333

React state is mutable, so you can update react state directly. But it is recommended not to mutate react state due to multiple reasons. One of the reasons is, if you do this.state.count = 3, react DOM will behave in an unpredictable manner such as overwriting data and not re-rendering. Performance tuning is another reason.

React on calling setState() will call the render method in some near future which will cause the DOM to be updated with new values.

Upvotes: 2

In javascript objects are mutable.

For example if

var a = {"something": 1}

and if you assign it to another variable b and if you change its value, the value of object a is also changed

var b = a;
b.something = 2;
console.log(b);
console.log(a);

//output {"something": 2}

both will print {"something": 2}. The value in a is also changed.

Similarly in your code you are directly assigning the state value in line number 61 and mutating it in line number 62.

So better way is to use

let newOptions = {...this.state.newOptions };

or

let newOptions = Object.assign({},this.state.newOptions}

This will create new object.

Upvotes: 2

Related Questions