My useEffect cleanup function isn't working properly, causing memory leaks. My interval keeps running after component unmounts: useEffect(() => { const interval = setInterval(() => { setData(fetchData()); }, 1000); return () => clearInterval(interval); }, []); The app crashes after navigating away multiple times. What's wrong?
// Correct implementation
useEffect(() => {
let isMounted = true;
const fetchDataSafely = async () => {
if (isMounted) {
const result = await fetchData();
setData(result);
}
};
const interval = setInterval(fetchDataSafely, 1000);
return () => {
isMounted = false;
clearInterval(interval);
};
}, []);
Always use a mounted flag to prevent state updates on unmounted components. This ensures proper cleanup and prevents memory leaks. Consider using React Query or SWR for better data fetching patterns.