Common side-effects that need cleanup in useEffect react hook
There are common asynchronous side-effects that are recommended to cleanup.
When a side-effect completes and react tries to update the state of an already unmounted component. This leads to a React warning:
Warning: Can't perform a React state update on an unmounted component.
1. Fetch requests
As already mentioned, it is recommended to abort the fetch request when the component unmount or updates.
Check the section?Canceling a fetch request?to find more information on how to properly cancel fetch requests.
2. Timer functions
When using?setTimeout(callback, time)?or?setInterval(callback, time)?timer functions, it's usually a good idea to clear them on unmount using the special?clearTimeout(timerId)?function.
3. Debounce and throttle
When debouncing or throttling event handlers in React, you may also want to make sure to clear any scheduled call of the debounced or throttled functions.
Usually the debounce and throttling implementations (e.g.?lodash.debounce,?lodash.throttle) provide a special method?cancel()?that you can call to stop the scheduled execution:
4. Web sockets
Another good candidate requiring cleanup are the?web sockets: