Today I Learned

hashrocket A Hashrocket project

Don't async await, especially in useEffect

Often I need to setState based on an async value. With hooks this is something like:

useEffect(async () => {
    const newVal = await asyncCall();

But wait!. This throws an error. React wants the return of useEffect to be a cleanup function.

The return type of an async function is Promise. So that won't work. Best to just put on your big developer pants and use that promise.

useEffect(() => {

There. Now our useEffect returns undefined, and React is pleased.

Here is a sandbox if you want to see for yourself.

See More #react TILs
Looking for help? At Hashrocket, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.