Use asynchronous function in React Hooks useEffect with Typescript

Anna Coding
Anna Coding
Published in
2 min readJan 9, 2020

When you use react hook, most probably you will have a case to use async function inside react hook.

import React, { useEffect } from 'react';

const ExampleFunctionnalComponent: React.FunctionComponent = (props) => {
useEffect(async () => {
await fetchData();
}, []);
return <div>
Something
</div>;
}

A wrong way to do it commonly

Well then Typescript will show an error 🤔as following:

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

The right way to use asynchronous function in useEffect😀:

const ExampleFunctionnalComponent: React.FunctionComponent = (props) => {
useEffect(() => {
const fetchDataAsync = async () => {
await fetchData();
}
fetchDataAsync()
}, []);
return <div>
Something
</div>;
}

Want to know the reason ?

Based on async function definition, we know that it returns an implicit Promise.

The async function declaration defines an asynchronous function — a function that returns an AsyncFunction object. Asynchronous functions operate in a separate order than the rest of the code via the event loop, returning an implicit Promise as its result. But the syntax and structure of code using async functions looks like standard synchronous functions.

💡But the function pass to useEffect callback normally need to return a clean function.in this case, implicit promise is not a clean function.

Effects create resources that need to be cleaned up before the component leaves the screen, such as a subscription or timer ID. To do this, the function passed to useEffect may return a clean-up function. https://reactjs.org/docs/hooks-reference.html#useeffect

--

--

Anna Coding
Anna Coding

Free web, mobile, DevOps, cloud tutorials, issues & solutions. www.annacoding.com