Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 956
Bill Avatar asked Jul 28 '19 07:07

Bill


People also ask

Can you make useEffect async?

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!

Can a React hook be async?

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.

Is useEffect synchronous?

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.


2 Answers

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

like image 125
Tobias Lins Avatar answered Oct 17 '22 06:10

Tobias Lins


You can use an IIFE (asynchronous anonymous function which executes itself) like so:

useEffect(() => {     // Some synchronous code.      (async () => {         await doSomethingAsync();     })();      return () => {         // Component unmount code.     }; }, []); 
like image 21
Daniel Avatar answered Oct 17 '22 06:10

Daniel