How to adjust for React.js handling state updates asynchronously

Calling `this.setState()` in a React component is fundamental to the framework. This is how the state is updated, and also triggers the re-rendering of the component. However, despite its familiarity, there are still some features that can create confusing behavior if you are unaware of them.
One such feature is that setState is asynchronous. Though updating the values of the state seems like a simple operation that wouldn’t need to be asynchronous, setState is handled asynchronously because it triggers re-rendering. This can get expensive if it’s done again and again, so processing state updates asynchronously allows React to batch state updates together in order to only trigger one re-render at the completion of all the updates.
How should we deal with this asynchronous behavior?
- If you are using the current state or props inside your setState call, pass an updater function (rather than an object) into setState to make sure that the right values are used even when updates are batched. See this example from the React documentation:
Javascript//Wrong
this.setState({ counter: this.state.counter + this.props.increment, });// Correct
this.setState((prevState, props) => ({ counter: prevState.counter + props.increment }));
- Put any code that needs to be executed after setState() into either:
- a callback function (passed as the second argument to setState, called when the state has finished updating).
- a React lifecycle hook that will be triggered after the state-change causes the component to re-render (such as componentDidMount or componentDidUpdate).
The most popular way to deal with asynchronous functions in JS is currently promises, but this is not recommended with setState. See Redux creator Dan Abramov’s comment about this for more details.
