Since React's setState is asynchronous, would it be recommendable to wrap its call in an async/await function, so that anything afterwards that critically depends on a state variable, would always get the updated value?
            Asked
            
        
        
            Active
            
        
            Viewed 1,263 times
        
    2
            
            
        - 
                    setState provides you a callback that you can use to make changes that depend on the current state. See this https://stackoverflow.com/questions/42038590/when-to-use-react-setstate-callback/42038724#42038724 – Shubham Khatri Aug 27 '17 at 07:12
2 Answers
2
            It would be a possible implementation of async/await. For example, inside your react component:
setStateAsync(state) {
  return new Promise((resolve) => {
    this.setState(state, resolve)
  });
}
async setStateAndDoSomethingRightAfter(state) {
    await this.setStateAsync({state})
    // now do something after
}
But I'm not sure if it would be recommendable. There are lifecycle methods for a reason.
I believe the "react" way of doing things is to put your code that's dependent on new state inside of componentDidMount / componentWillUpdate / componentDidUpdate.
 
    
    
        DoloMike
        
- 499
- 6
- 15
- 
                    1We can directly use `await this.setState({state})`. No need to create such wrapper functions like setStateAsync! – Aniruddha Shevle Mar 01 '19 at 05:46
 
     
    