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

React + Firestore : Get Setup In Five Steps

One of the biggest barriers to learning React used to be the overwhelming amount of tooling involved. Beginners were forced to make important decisions about things they don’t understand before they could create anything. React solved... Continue →