How to use async function in useEffect hook?
Bunlong
React Patterns Team#
How to use async function in useEffect hook?At first glance you will have an idea as following.
What's wrong?
The compiler should be yielding something as following.
Do you start seeing the problem here? Let's take a look the useEffect hook to get more informations.
The problem is useEffect
expects a clean-up function in return to clear the created resources before the component leaves the screen, but when we use async function it return a promise instead.
#
How to deal with async function in useEffect hook?You can define an async function inside useEffect
and then call it over there as following.
You can also us an IIFE (Immediately Invoked Function Expression) as following.