2

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?

vk23
  • 468
  • 7
  • 16
Kevin Barasa
  • 71
  • 1
  • 10
  • 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 Answers2

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
2

You can use the second parameter of setState, a callback. DOCS.
this.setState({ key: val }, callBack)

Sagiv b.g
  • 30,379
  • 9
  • 68
  • 99