I did not see this question addressed in the lesson about setState() and for some reason I can’t post in the React.js FAQ (why?)
My question was, why do we have to use setState() to update a component’s state, instead of setting it directly? According to React.Component documentation:
this.state directly, as calling
setState() afterwards may replace the mutation you made. Treat
this.state as if it were immutable.
This article goes into more depth on this.
It’s complicated, and I’ll admit that I don’t have a complete understanding of it, but the main reason is that React has its own ways of handling state updates, and setting state directly or mutating state circumvents these.
One part of it is that React automatically batches certain actions together in order to reduce the number of renders that state changes might cause. So doing a few at once may be more efficient than 3 or 4 one after another. Setting the state directly interferes with this process.
This is the best answer, but it’s complex enough to demonstrate that this is not something a junior dev would need to know to understand their code: