DEV Community


Discussion on: 💡 React Hooks: async function in the useEffect

symaticvisuals profile image
Deepanshu Goel

Hey, I didn't understand the concept thoroughly. Can you explain a little bit more.

danialdezfouli profile image
Danial Dezfouli Author • Edited

Some developers tried to use async functions in useEffect and got warnings/bugs with the following code:

Anti-Pattern: async function directly in the Hook

useEffect(async () => {
await fetch(EXAMPLE_URL)
}, []);
Enter fullscreen mode Exit fullscreen mode

I have explained the reason why eslint shows warnings and our cleanup function will not run (because of the async function).

Async functions have to be written in the callback as follows:

useEffect(() => {
    (async () => {
      const products = await api.index()
  }, [])
Enter fullscreen mode Exit fullscreen mode
Forem Open with the Forem app