DEV Community

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

Collapse
 
samthecodingman profile image
Samuel Jones

A simplistic way to dump the result would be to track whether the useEffect's unsubscribe function has been called using:

useEffect(() => {
  let disposed = false

  (async () => {
    const products = await api.index()

    if (disposed) return

    setFilteredProducts(products)
    setProducts(products)
  })()

  return () => disposed = true
}, [])
Enter fullscreen mode Exit fullscreen mode

But as others have said, Redux is often the way to go if you are doing this often and there are also the use-async-effect and @react-hook/async packages for useAsyncEffect implementations.