Beware: React setState is asynchronous!
Tomas Carnecky
231

This is really helpful, and using the callback form of `setState` helped me out recently with a bug I was having where pending state updates were getting overwritten by logic in `componentWillReceiveProps`. Thanks for sharing!

I also wanted to point out that the first form of using setState you reference, e.g. `this.setState({ …this.state, foo: 42 });`, is likely to lead to more conflicts in updating different parts of your state. With setState, it’s simpler and safer to just pass in the state you want to update, e.g. `this.setState({ foo: 42 });`. The rest of the state will remain untouched.

(Update: Thanks for pointing out that replaceState isn’t actually available in React.Component subclasses and is likely to be removed. I removed that part of the comment)

Show your support

Clapping shows how much you appreciated Andrew Patton’s story.