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)
Either way, we're now safe to use async functions inside useEffect hooks. Now if/when you want to return a cleanup function, it will get called and we also keep useEffect nice and clean and free from race conditions. Enjoy using async functions with React's useEffect from here on out!
React can run this async function but can not run the cleanup function. Don't use raw async function directly in the useEffect. useEffect(async () => { console.
The useLayoutEffect function is triggered synchronously before the DOM mutations are painted. However, the useEffect function is called after the DOM mutations are painted. I chose this example to make sure the browser actually has some changes to paint when the button is clicked, hence the animation.
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 an IIFE (asynchronous anonymous function which executes itself) like so:
useEffect(() => { // Some synchronous code. (async () => { await doSomethingAsync(); })(); return () => { // Component unmount code. }; }, []);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With