React TypeScript 16.8 How to make useEffect() async

ReactjsTypescriptAsync AwaitReact Hooks

Reactjs Problem Overview


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)

Reactjs Solutions


Solution 1 - Reactjs

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

Solution 2 - Reactjs

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

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

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

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

Solution 3 - Reactjs

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()
  })()
}, []);

Solution 4 - Reactjs

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBillView Question on Stackoverflow
Solution 1 - ReactjsTobias LinsView Answer on Stackoverflow
Solution 2 - ReactjsDanielView Answer on Stackoverflow
Solution 3 - ReactjsNikhil BhandarkarView Answer on Stackoverflow
Solution 4 - ReactjsDanielView Answer on Stackoverflow