28
votes

Why can't useEffect() use async-await?

const Home: React.FC = () => {
    
    useEffect(async () => {
        console.log(await ecc.randomKey())
    }, [])
    
    return (
    ...

The error I get is

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

Type 'Promise' is not assignable to type 'void | (() => void | undefined)'.

Type 'Promise' is not assignable to type '() => void | undefined'.

Type 'Promise' provides no match for the signature '(): void | undefined'.ts(2345)

4

4 Answers

24
votes

Declaring the effect as async function is not recommended. But you can call async functions within the effect like following:

useEffect(() => {
  const genRandomKey = async () => {
    console.log(await ecc.randomKey())
  };

  genRandomKey();
}, []);

More here: React Hooks Fetch Data

7
votes

You can use an asynchronous anonymous function which executes itself like so:

useEffect(() => {
    // Some synchronous code.

    (async () => {
        await doSomethingAsync();
    })();

    return () => {
        // Component unmount code.
    };
}, []);
5
votes

Why

Using an async function in useEffect makes the callback function return a Promise instead of a cleanup function.

Solution

useEffect(() => {
  const foo = async () => {
    await performPromise()
  };

  foo();
}, []);

OR with IIFE

useEffect(() => {
  (async () => {
    await performPromise()
  })()
}, []);
0
votes

You can use the use-async-effect package which provides a useAsyncEffect hook:

useAsyncEffect(async () => {
  await doSomethingAsync();
});