**How to correctly use useEffect for cleanup operations during component unmounting in React**
---
**Answer and Explanation:**
In React, the `useEffect` hook is used to execute side effects such as data fetching, timers, event listeners, or other asynchronous operations when a component mounts, updates, or unmounts. When a component unmounts, asynchronous operations (e.g., API requests, timers, event subscriptions) must be cleaned up to prevent memory leaks or unintended state updates to already unmounted components.
The correct practice is to return a cleanup function from the `useEffect` callback. React automatically calls this cleanup function before the component unmounts.
---
**Example:**
```jsx
import { useEffect, useState } from 'react';
function MyComponent() {
const [data, setData] = useState(null);
useEffect(() => {
let isMounted = true; // Prevent state updates after unmount
fetch('/api/data')
.then(res => res.json())
.then(result => {
if (isMounted) {
setData(result);
}
});
// Cleanup function
return () => {
isMounted = false; // Indicate component has unmounted
};
}, []);
return {data ? data.message : 'Loading...'}
;
}
```
---
**Key Points Explanation:**
1. **Return a cleanup function**
The `useEffect` hook returns a cleanup function that is executed before the component unmounts. This ensures proper resource cleanup.
2. **Avoid state update warnings**
If you update the state in an asynchronous callback after the component has unmounted, React will throw a warning. Using `isMounted` prevents this issue.
3. **Use cases**
Cleanup functions are essential for scenarios like:
- Timers (`setTimeout`, `setInterval`)
- Subscriptions (e.g., to event streams)
- WebSocket connections
- Global event listeners
---
**Note:** In React 18's strict mode, the development environment intentionally re-mounts and unmounts components multiple times to help identify potential issues. Properly implementing cleanup logic is critical in this mode.