DEV Community


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

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.

danialdezfouli profile image
Danial Dezfouli Author

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

Thread Thread
icyjoseph profile image

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.

Forem Open with the Forem app