SolvedDefinitelyTyped [@types/react] useEffect(async () => ...) does not account for async

If you know how to fix the issue, make a pull request instead.

Right now I am unable to make function that useEffect takes in as async, since it returns following error:

[ts]
Argument of type '() => Promise' is not assignable to parameter of type 'EffectCallback'.
Type 'Promise' is not assignable to type 'void | (() => void)'.
Type 'Promise' is not assignable to type '() => void'.
Type 'Promise' provides no match for the signature '(): void'. [2345]

Example

useEffect(async () => {
  await ...
})

Judging by what I've googled async function inside useEffect is a valid option?

14 Answers

✔️Accepted Answer

Instead of this

const doStuff = async () => {...}

useEffect( () => doStuff())

try this:

const doStuff = async () => {...}
useEffect( () => { doStuff() } )

I had the same issue and it helped.

Other Answers:

A very useful custom hook:

function useAsyncEffect(effect: () => Promise<void | (() => void)>, dependencies?: any[]) {
  return useEffect(() => {
    const cleanupPromise = effect()
    return () => { cleanupPromise.then(cleanup => cleanup && cleanup()) }
  }, dependencies)
}

@rauldeheer thanks for the package but I think it would be better if we could use async without add extra dependencies. Anyways I'll use your package for now.

Why is this closed? Having issues with this too.

Hi! You can now easily use the async await syntax with the React useEffect hook with this package. I hope this will help you, and others.

Cheers 🎉 !

More Issues: