What are common cleanup scenarios?

0123

Common cleanup scenarios in React components using the useEffect hook include:

  1. Clearing Timers: If you set up a timer using setTimeout or setInterval, 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);
    }, []);
  2. 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);
        };
    }, []);
  3. 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
        };
    }, []);
  4. 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
        };
    }, []);
  5. 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.

0 Comments

no data
Be the first to share your comment!