How to use async function in useEffect hook?

Bunlong

Bunlong

React Patterns Team

How to use async function in useEffect hook?

How to use async function in useEffect hook?#

At first glance you will have an idea as following.

useEffect(async () => {
await someTask();
}, []);

What's wrong?

The compiler should be yielding something as following.

Argument of type '() => Promise<void>' is not assignable to parameter of type 'EffectCallback'.

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.

useEffect(() => {
// Create an scoped async function in the hook
async anyNameFunction() => {
await someTask();
}
// Execute the created function directly
anyNameFunction();
}, []);

You can also us an IIFE (Immediately Invoked Function Expression) as following.

useEffect(() => {
(async anyNameFunction() => {
await someTask();
})();
}, []);