Here’s an example that demonstrates how to use the useEffect hook with a cleanup function:

import React, { useState, useEffect } from 'react';

const MyComponent = () => {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log('Component mounted');

    // Cleanup function
    return () => {
      console.log('Component unmounted');
    };
  }, []);

  const incrementCount = () => {
    setCount((prevCount) => prevCount + 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={incrementCount}>Increment</button>
    </div>
  );
};

In this example, the useEffect hook is used to log a message when the component mounts. The effect has an empty dependency array [], which means it will only run once when the component is mounted.

The useEffect hook also accepts a cleanup function, which is returned from the effect. In this case, the cleanup function logs a message when the component is unmounted. The cleanup function is useful for cleaning up any resources or subscriptions created within the effect to avoid memory leaks.

When the component is rendered, the count value is displayed, and clicking the “Increment” button will update the count state using the setCount function.

To see the cleanup function in action, you can open the browser console. When the component is mounted, you’ll see the “Component mounted” message logged. When the component is unmounted (e.g., if you navigate away from the page or remove the component from the DOM), the “Component unmounted” message will be logged.

The cleanup function ensures that any resources or subscriptions created within the effect are properly cleaned up when the component is no longer needed, preventing memory leaks and maintaining good performance.