https://facebook.github.io/react/docs/react-component.html#setstate
It's also possible to pass a function with the signature function(state, props) => newState. This enqueues an atomic update that consults the previous value of state and props before setting any values. For instance, suppose we wanted to increment a value in state by props.step:
this.setState((prevState, props) => {
return {myInteger: prevState.myInteger + props.step};
});
What is meant by atomic update here? Isn't JavaScript a single threaded language? Which means that all the updates are bound to be atomic?
Single threaded yes, but also with lots of potential asynchronicity.
setState
is an asynchronous call, so it's possible thatstate
has changed since it gets executed.Perhaps a different wording that would apply is that the callback function enqueues a transactional update, though I think any fancy wording could be confusing here. It's best to just explain that state may have changed, so the callback has the exact snapshot of the previous state.