Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What if you can use async/await to make React's setState synchronous

Tags:

reactjs

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 });

like image 404
l0rdcafe Avatar asked Oct 31 '18 09:10

l0rdcafe


1 Answers

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.

like image 79
Estus Flask Avatar answered Sep 18 '22 07:09

Estus Flask