// Tutorial //

Atomic SetState Updates in React

Published on July 26, 2017
Default avatar
By William Le
Developer and author at DigitalOcean.
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


Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

Sign up
About the authors
Default avatar
Developer and author at DigitalOcean.

Still looking for an answer?

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!