DEV Community

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

Collapse
 
symaticvisuals profile image
Deepanshu Goel

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

Collapse
 
danialdezfouli profile image
Danial Dezfouli • 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()
      setProducts(products)
    })()
  }, [])
Enter fullscreen mode Exit fullscreen mode