Want a new VS Code theme?

Setting state based on previous state

August 08, 2018

Let’s say that you’re making a React popup that toggles itself. Most people would check against the current state to toggle the new one:

// Potentially hazardous
toggle() {
  this.setState({ show: !this.state.show })

However, this could potentially lead to a bug because this.setState is asynchronous. this.state.show might’ve not updated yet1. Luckily, the fix is simple:

// You deserve a promotion
toggle() {
  this.setState((prevState, props) => ({
    showForm: !prevState.showForm
  1. In this example, it’s likely that it already changed. However, in a complex application with lots of calls to this.state, a bug could eventually occur. ↩︎