DEV Community

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

Collapse
 
valeriavg profile image
Valeria

As it was already mentioned in the comments, having raw async functions in the useEffect is always a bad idea. Once created, the promise cannot be stopped, it will inevitably resolve or fail, even if the component itself is long gone.
In other words, one needs to make sure that when promise results are evaluated the mounted state is taken into consideration or that errors are properly silenced

Collapse
 
elmehdiyessad profile image
elmehdi

Hey in order to get data once and prevent useEffect hook that render the data in the infinite loop you should just initialize an empty array as a second argument to the useEffect hook like this

useEffect(() => {
// use code here
}, [])

Collapse
 
digitalbrainjs profile image
Dmitriy Mozgovoy

having raw async functions in the useEffect is always a bad idea
Once created, the promise cannot be stopped

Unless you're using async effects with cancelable promises :)

Collapse
 
raibtoffoletto profile image
Raí B. Toffoletto

Exactly... and then the console yells at you that there's a state changed in a unmounted component and that's a memory leak bug in the app.

After sometime experimenting with api call in useEffect at work we got to the conclusion that any async logic state goes to Redux. Better to have a more complex and organized store and leave components with simple logic.

Collapse
 
danialdezfouli profile image
Danial Dezfouli

As Samuel mentioned, we can check if the component is unmounted or not to update the state.

Thread Thread
 
icyjoseph profile image
Joseph

Not really... You shouldn't really be doing handcrafted isMounted checks at all. To prevent state updates from an unstoppable promise/async function, use a ref on an HTML element on whatever you are rendering on this component, if the ref.current value is null then throw in the promise or exit the async function gracefully, skipping any updates.

Of course for fetch/axios there's a proper abort/cancel mechanism.