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.

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay