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 });
There are no pros because this.setState
doesn't return a promise and await
ing 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With