How does useEffect handle component unmounting?

0124

The useEffect hook can handle component unmounting by returning a cleanup function. This cleanup function is executed when the component is about to unmount or before the effect runs again due to a change in dependencies. This is useful for cleaning up resources such as timers, subscriptions, or event listeners that were set up in the effect.

Here's how it works:

  1. Return a Cleanup Function: Inside the useEffect callback, you can return a function. This function will be called when the component unmounts or before the effect is re-run.

  2. Cleanup on Unmount: When the component is removed from the DOM, React will call the cleanup function, allowing you to perform any necessary cleanup.

Here's an example:

import React from 'react';

const TimerComponent = () => {
    const [count, setCount] = React.useState(0);

    React.useEffect(() => {
        const timer = setInterval(() => {
            setCount(prevCount => prevCount + 1);
        }, 1000);

        // Cleanup function to clear the timer
        return () => {
            clearInterval(timer);
            console.log('Timer cleared');
        };
    }, []); // Empty dependency array means this effect runs once on mount

    return (
        <div>
            <p>Count: {count}</p>
        </div>
    );
};

export default TimerComponent;

In this example:

  • A timer is set up using setInterval to increment the count state every second.
  • The cleanup function returned from useEffect calls clearInterval(timer) to stop the timer when the component unmounts.
  • This prevents memory leaks and ensures that the timer does not continue running after the component is removed from the DOM.

0 Comments

no data
Be the first to share your comment!