Elegant “async memory leaks fix” with React Hooks
Warning: Can’t perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
This problem is usually related with updating states in asynchronous tasks and represents a familiar scenario when working with React Hooks.
The previous component is candidate to cause warning memory leaks because is updating the state in an asynchronous task out of control. To solve it, we need to prevent state updates when the component is no longer mounted. It can be done while using a reference to know if the component has been unmounted just before updating the state.
Although it looks like a good a solution, our application will probably have other similar scenarios, so a good practice would be always implement a reusable, elegant, efficient and simple solution: custom hook which will be responsible of execute safely the async callback and maintain its execution result, the loading state and the update state callback.
Our custom async hook
Usage examples:
This hook can be modified to work with other requirements, like saving/retrieving the state through the local storage.