I understand that React tutorials and documentation warn in no uncertain terms that state should not be directly mutated and that everything should go through setState
.
I would like to understand why, exactly, I can't just directly change state and then (in the same function) call this.setState({})
just to trigger the render
.
E.g.: The below code seems to work just fine:
const React = require('react');
const App = React.createClass({
getInitialState: function() {
return {
some: {
rather: {
deeply: {
embedded: {
stuff: 1,
},
},
},
},
},
};
updateCounter: function () {
this.state.some.rather.deeply.embedded.stuff++;
this.setState({}); // just to trigger the render ...
},
render: function() {
return (
<div>
Counter value: {this.state.some.rather.deeply.embedded.stuff}
<br></br>
<button onClick={this.updateCounter}>Increment</button>
</div>
);
},
});
export default App;
I am all for following conventions but I would like to enhance my further understanding of how ReactJS actually works and what can go wrong or is it sub-optimal with the above code.
The notes under the this.setState
documentation basically identify two gotchas:
- That if you mutate state directly and then subsequently call
this.setState
this may replace (overwrite?) the mutation you made. I don't see how this can happen in the above code. - That
setState
may mutatethis.state
effectively in an asynchronous / deferred way and so when accessingthis.state
right after callingthis.setState
you are not guaranteed to access the final mutated state. I get that, by this is not an issue ifthis.setState
is the last call of the update function.