React setState takes an updater function

If you increment a count in state using a state update function 3 times then the final count will be 3.

state = {count: 0}

this.setState( previousState => ({count: previousState.count++}))
this.setState( previousState => ({count: previousState.count++}))
this.setState( previousState => ({count: previousState.count++}))

this.state.count = 3

If you increment state 3 times just using a regular object then the changes will get batched together. Something that often gets overlooked is that setState  is asynchronous. State may not change immediately on calling setState because react batches state changes for performance.

state = {count: 0}

this.setState( { count: this.state.count++})
this.setState( { count: this.state.count++})
this.setState( { count: this.state.count++})

this.state.count = 1

The rule is if you need to reference current state then use an updater function, if you don’t then you can just use an object. If you don’t like having complicated rules then just always use an updater function.

Kent C. Dodds

 
3
Kudos
 
3
Kudos

Now read this

Information Onslaught

There are physical limitations to how much I can learn in one go. My brain just fizzles out and the simplest things stop making sense. The first week at Founders and Coders has been intense. The cohort was split into groups of four and... Continue →