React.Component setState atomic updates

1.9k views Asked by At

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?

1

There are 1 answers

0
azium On

Single threaded yes, but also with lots of potential asynchronicity.

let atom = 10
atom = 20
console.log(atom) // guaranteed to be 20, so "atomic"

// race condition
setTimeout(() => atom = 30, Math.random() * 1000)
setTimeout(() => atom = 40, Math.random() * 1000)

setTimeout(() => console.log(atom), 2000) // 30? or 40? random!

setState is an asynchronous call, so it's possible that state 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.