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: ! })

However, this could potentially lead to a bug because this.setState is asynchronous. 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. ↩︎

Want more?

My newsletter sends rarely. It's where I share updates on the best of my writing: introverted entrepreneurship, esoteric mindset tips, notes from great books, and automating businesses as a solo-owner so they run by themselves. Want to join?