React TypeScript 16.8 How to make useEffect() async
ReactjsTypescriptAsync AwaitReact HooksReactjs 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
> Type 'Promise
> Type 'Promise
> Type 'Promise
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();
});