Bill
Bill

Reputation: 5150

React TypeScript 16.8 How to make useEffect() async

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)

Upvotes: 74

Views: 76798

Answers (4)

yoty66
yoty66

Reputation: 746

I read the answers and all the answers are correct but the "native ones" (the ones not using a third-party package) don't allow you to do two things:

  1. Optimize the effect handler using useCallback (because a hook can only be used on the top level)
  2. Reuse the effect handler in other places.

I found this method which enables both

const Component= ()=>{
  const effectHandler = async()=>{
    // Do some async stuff
   }

  useEffect(()=>{
      effectHandler()
   }, [])


  // reuse effectHandler
   effectHandler()

  return(<></>)
}

Upvotes: 0

Daniel
Daniel

Reputation: 9504

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

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

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

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

Upvotes: 41

Daniel
Daniel

Reputation: 9504

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

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

Upvotes: 1

Tobias Lins
Tobias Lins

Reputation: 2651

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

Upvotes: 89

Related Questions