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

5 Months of Learning to Code

Total Days 137 Total Earned $2135 This year I committed to earning at least $10,000 learning how to code. I am now in the middle of my fifth month. Last Tuesday I got accepted into Founders and Coders. A 16-week boot camp in London that... Continue →