Tutorial

Atomic SetState Updates in React

Published on July 26, 2017
Default avatar

By William Le

Atomic SetState Updates in React

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

SetState has a notorious reputation for misleading newcomers to believe that state updates are synchronous. While setState is very fast at computing state via it’s reconciliation algorithm it’s nonetheless an asynchronous operation that, if used improperly, can make it very challenging to manage complex state in React components. In this article, learn about setState's lesser-known functional signature that will guarantee atomic state updates

SetState Classic™

If you’ve been using React for a while you may have had encountered situations like this:

/*
The initial value of
this.state.count = 0
*/

// multiple calls
this.setState(count: this.state.count + 1);
this.setState(count: this.state.count + 1);
console.log(this.state.count); // 1

// for-loop
for (let i = 0; i < 10; i++) {
  this.setState({count: this.state.count + 1});
}
console.log(this.state.count); // 1

// if-statement
this.setState({count: this.state.count + 1});
if (this.state.count === 0) {
  console.log(this.state.count);  // 0
}

SetState has caused a lot of confusion for newcomers to the React community. A quick search on StackOverflow using the keywords “react setstate” shows there’s still haziness about whether setState is asynchronous or synchronous. Eric Elliot even suggested avoiding setState all together and just letting Redux handle all state updates.

And the discontent is partly justified. In the official React documentation, this classic way of passing setState an object literal is prone to introducing “race condition” bugs that are difficult to fix. This problem is compounded when your components have a lot of state to manage.

Silly state illustration

Functional SetState

There’s another way to use setState that isn’t advertised very prominently in the docs.

this.setState((prevState) => {
  return {count: prevState.count + 1};
})
this.setState((prevState) => {
  return {count: prevState.count + 1};
})
this.setState((prevState) => {
  return {count: prevState.count + 1};
})
this.setState((prevState) => {
  console.log(prevState.count);  // 3
  return {count: prevState.count + 1};
})

If you haven’t seen this before, you’d be right to think I was making this up, but I assure you it’s real. By passing in a function (instead of the familiar object literal) it’ll get the current state tree as the first argument and have an opportunity to perform its own arbitrary computations before it passes control to successive setState calls. In other words, these functions are guaranteed to receive atomic state updates.

“It is safe to call setState with a function multiple times. Updates will be queued and later executed in the order they were called.” – Dan Abramov

This way of using setState gives us predictable & reliable ways to manipulate state in React. While it’s more verbose, it becomes indispensable if you’re working with large state trees and/or sophisticated logic to update state.

Let’s explore a real-world example so that we can compare both approaches.

password box illustration

Building a Password Validator

Imagine that you’re building a form to let users reset their password. We’ll need to hold several pieces of state; most of which are for validating password strength.

class PasswordForm extends Component {

  constructor(props) {
    super(props);
    this.state = {
      password: '',
      hasEnoughChars: false,
      hasUpperAndLowercaseChars: false,
      hasSpecialChars: false,
      isPasswordValid: false
    };
  }

  render() {
    return (
      <div>

        /*input*/
        <input onChange={this.handleInput} type="password" value={this.state.password}/>

        /*visual prompts*/
        <div>
          <span style={bgColor(this.state.hasEnoughChars)}>
            Minimum 8 characters
          </span>
          <span style={bgColor(this.state.hasUpperAndLowercaseChars)}>
            Include 1 uppercase and lowercase letter
          </span>
          <span style={bgColor(this.state.hasSpecialChars)}>
            Minimum 1 special character
          </span>
        </div>

        /*button*/
        <button disabled={!this.state.isPasswordValid}>
          Submit
        </button>

      </div>
    );
  }

  bgColor(condition) {
    return {backgroundColor: condition ? 'green' : 'red'};
  }

  // Object literal & Callback
  handleInput(e) {

    this.setState({
      password: e.target.value,
      hasEnoughChars: e.target.value.length >= 8,
      hasUpperAndLowercaseChars: /[a-z]/.test(e.target.value) && /[A-Z]/.test(e.target.value),
      hasSpecialChars: /[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/.test(e.target.value)
    }, () => {

      if (this.state.hasEnoughChars && this.state.hasUpperAndLowercaseChars && this.state.hasSpecialChars) {
        this.setState({isPasswordValid: true});
      }
      else {
        this.setState({isPasswordValid: false});
      }
    });
  }

  // Functions
  handleInput(e) {

    this.setState({password: e.target.value});

    this.setState((prevState) => ({
      hasEnoughChars: prevState.password.length >= 8,
      hasUpperAndLowercaseChars: /[a-z]/.test(prevState.password) && /[A-Z]/.test(prevState.password),
      hasSpecialChars: /[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/.test(prevState.password)
    }));

    this.setState((prevState) => ({
      isPasswordValid: prevState.hasEnoughChars
        && prevState.hasUpperAndLowercaseChars
        && prevState.hasSpecialChars
    }));
  }
}

Using callbacks puts us in the mindset of managing the order of things by nesting functions. While it doesn’t look that bad right now, if we needed to add a callback after this.setState({isPasswordValid}) things get ugly pretty quickly.

Using functions each setState is tailored for one area of concern. For this reason, we don’t need to “hard code” the order of state updates inside these function definitions since all of the relevant information you need to transition state is provided in the first argument: prevState.

Wrapping Up

By using this function signature for setState you’re working directly with the latest state tree. This predictability enables us to reason about the problem more effectively, and build state-rich React components with confidence.

Give this pattern a try and see if you like it. There’s a chance this way of using setState will become de-facto. In a tweet, Dan Abramov suggested that “it’s likely that in the future React will eventually support this pattern more directly.”

👉 Check out the CodePen of the password form

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
William Le

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel