reactjstypescriptasync-awaitreact-hooks

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)


Solution

  • 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