Setting (mutating) the state directly will work in this case:
this.state.myVar = 'changed state'
However, it should be avoided according to the React docs:
NEVER mutate this.state
directly, as calling setState()
afterwards may replace the mutation you made. Treat this.state
as if it were immutable.
The main problem with mutating the state is that it prevents some of the React lifecycle methods from working. For example, React's shouldComponentUpdate()
method is often used to speed up the app when dealing with a large number of components. The method allows you to skip re-rendering a component if the state has been updated:
// Return false if you want to skip the `render()` method
shouldComponentUpdate: function(nextProps, nextState) {
return this.state.myVar === nextState.myVar;
}
The above will not work if you are mutating the state. this.state.myVar
and nextState.myVar
references are the same and therefore the above will always return true
.