setState is asynchronous

A gentle introduction to setState, for React developers, pt 1.

setState is asynchronous.

“Asynchronous” is a big word. So what does it mean in practice?

It means you can’t call setState on one line and assume state has changed on the next.

setState({ name: "Michael" });

console.log(this.state.name); // Nope.

You’ll likely log the previous, unchanged state. This probably isn’t what you expected. You expected the next state—the updated state.

So how do we get that?

If you love something, set it free.

Embrace your inner determinist.

Think of setState as setStateFree . Set state free and it’ll come back in the next render.

componentDidUpdate(_, previousState) {

console.log(previousState); // => {}

console.log(this.state); // => { name: "Michael" }

}

Once setState is called, don’t interact with state until the next render.

Previous, current, and next, oh my!

Working with state can be tricky—no doubt.

That pain isn’t telling you to install a library. It’s telling you to learn more about a component lifecycle methods.

shouldComponentUpdate , componentWillUpdate , and componentDidUpdate are where you’ll interact with the various states of state.

Read up!