React TypeScript 16.8 How to make useEffect() async
You can use an IIFE (asynchronous anonymous function which executes itself) like so:
useEffect(() => {
// Some synchronous code.
(async () => {
await doSomethingAsync();
})();
return () => {
// Component unmount code.
};
}, []);
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
You can use the use-async-effect
package which provides a useAsyncEffect
hook:
useAsyncEffect(async () => {
await doSomethingAsync();
});