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
The React docs for setState have this to say:
NEVER mutate
this.state
directly, as callingsetState()
afterwards may replace the mutation you made. Treatthis.state
as if it were immutable.
setState()
does not immediately mutatethis.state
but creates a pending state transition. Accessingthis.state
after calling this method can potentially return the existing value.There is no guarantee of synchronous operation of calls to
setState
and calls may be batched for performance gains.
setState()
will always trigger a re-render unless conditional rendering logic is implemented inshouldComponentUpdate()
. If mutable objects are being used and the logic cannot be implemented inshouldComponentUpdate()
, callingsetState()
only when the new state differs from the previous state will avoid unnecessary re-renders.
Basically, if you modify this.state
directly, you create a situation where those modifications might get overwritten.
Related to your extended questions 1) and 2), setState()
is not immediate. It queues a state transition based on what it thinks is going on which may not include the direct changes to this.state
. Since it's queued rather than applied immediately, it's entirely possible that something is modified in between such that your direct changes get overwritten.
If nothing else, you might be better off just considering that not directly modifying this.state
can be seen as good practice. You may know personally that your code interacts with React in such a way that these over-writes or other issues can't happen but you're creating a situation where other developers or future updates can suddenly find themselves with weird or subtle issues.