9

Since React's setState function is asynchronous and therefore, you cannot access newly updated state within the same function calling this.setState, what are the pros and cons of using async/await on setState, like await this.setState({ newState });

l0rdcafe
  • 101
  • 1
  • 6
  • if you really wanted to you could wrap your setstate with a promise.. and resolve when the setstate is completed. that would be something you could use async await on :) – John Ruddell Oct 31 '18 at 10:33
  • 1
    @JohnRuddell, you don't need to wrap it into a promise and use await since it already provides a callback to take actions when setState is completed – Shubham Khatri Oct 31 '18 at 11:10

2 Answers2

17

There are no pros because this.setState doesn't return a promise and awaiting it doesn't serve a good purpose.

It should be promisified in order to be used with await:

const setStateAsync = updater => new Promise(resolve => this.setState(updater, resolve))

There usually won't be much use of this due to how setState is usually used. If there's a need to rely on previously set state, updater function may be used.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
10

await keyword needs to be used for an expression that returns a Promise, and although setState is async, it doesn't return a Promise and hence await won't work with it. setState provides a callback to track if it has completed.

You would use callback like

this.setState({
   newState
}, () => {
    console.log(this.state.newState)
})

Here is a demo which shows that setState doesn't work with async await

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • It works if you promisify the state correctly and then await on it. https://codesandbox.io/s/4wxoyrpknw – Anurag Awasthi Oct 31 '18 at 11:10
  • 1
    @nrgwsth I know it will work if you promisify the action, but you don't need to do it as it provided a callback already and wrapping it into a promise just so that you can make use of await don't make sense. It would introduce too may complications in your app. setState callback along with other lifecycle methods tend to solve most of the problems – Shubham Khatri Oct 31 '18 at 11:11