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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With