Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change single variable of react state

Is it allowed to assign a single variable of react component state like this.state.foo = "bar" without calling setState? I need to change part of the state in multiple places, and I'm unable to use object spread operator and Object.assign is too verbose. How to change just a part of the state without redefining the whole state?

like image 818
Tuomas Toivonen Avatar asked Jul 04 '16 11:07

Tuomas Toivonen


1 Answers

You should use setState rather than instance variables because it is important that React knows about state changes so that it can trigger renders appropriately.

Because of the diffing algorithm React uses on the DOM it is efficient to call setState as often as you like.

Note that calling setState on one variable will leave the others unchanged:

this.setState({ foo: 'bar' }); // Does not change foo2
like image 188
sdgfsdh Avatar answered Sep 28 '22 01:09

sdgfsdh