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

Rules to Code By

If you’re relatively new to programming: Choose a language and stick to it. Choose a text editor that is easy to learn and stick to it. Avoid large frameworks like Rails and Django until you’ve got a decent grasp on the language you’re... Continue →