Common cleanup scenarios in React components using the useEffect hook include:
-
Clearing Timers: If you set up a timer using
setTimeoutorsetInterval, you should clear it in the cleanup function to prevent it from running after the component unmounts.useEffect(() => { const timer = setInterval(() => { // Some logic }, 1000); return () => clearInterval(timer); }, []); -
Removing Event Listeners: If you add event listeners (e.g., for window resize or scroll events), you should remove them in the cleanup function to avoid memory leaks.
useEffect(() => { const handleResize = () => { // Handle resize }; window.addEventListener('resize', handleResize); return () => { window.removeEventListener('resize', handleResize); }; }, []); -
Cancelling API Requests: If you initiate an API request, you may want to cancel it if the component unmounts before the request completes. This can be done using an
AbortController.useEffect(() => { const controller = new AbortController(); const signal = controller.signal; fetch('/api/data', { signal }) .then(response => response.json()) .then(data => { // Handle data }) .catch(err => { if (err.name === 'AbortError') { console.log('Fetch aborted'); } }); return () => { controller.abort(); // Cancel the fetch request }; }, []); -
Cleaning Up Subscriptions: If you subscribe to a data source (like a WebSocket or a third-party library), you should unsubscribe in the cleanup function.
useEffect(() => { const subscription = someDataSource.subscribe(data => { // Handle incoming data }); return () => { subscription.unsubscribe(); // Unsubscribe on cleanup }; }, []); -
Resetting State: In some cases, you may want to reset certain state variables when the component unmounts.
useEffect(() => { // Some logic return () => { setSomeState(initialValue); // Reset state on unmount }; }, []);
These cleanup scenarios help ensure that your components manage resources efficiently and avoid potential memory leaks or unintended behavior.
