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

 
1
Kudos
 
1
Kudos

Now read this

Switching Between Staging and Production Firebase Deploys In A Create-React-App

When building web applications on firebase, it is always a good idea to push the final application to the brand new firebase project. Go into your firebase console and setup a new firebase project. Explicitly name this project... Continue →