DEV Community

Cover image for How to use async function in useEffect?
Bond
Bond

Posted on

How to use async function in useEffect?

Install ahooks and use useAsyncEffect.

Example:

  useAsyncEffect(async () => {
    setUser(await getUser());
  }, []);
Enter fullscreen mode Exit fullscreen mode

Note: This is bad practice. You should try other techniques instead of trying to run async functions inside useEffect.

Top comments (2)

Collapse
 
cookiemonsterdev profile image
Mykhailo Toporkov πŸ‡ΊπŸ‡¦

Just why? It a bad approach to fetch data inside useEffect... We have so many better solutions that are in-build in libs or frameworks like next.js, react-router-dom, tanstack query etc, just do not get the point.

Collapse
 
bondaspecta profile image
Bond

That's correct. Let me mark it as bad practice and let's forget about this feature.