Q&A React useEffect Memory Leak

React useEffect cleanup causing memory leak

2 days ago
Expert verified
React

Question

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?

Answer

The issue is that fetchData() returns a Promise, but you're setting it directly to state. This creates memory leaks because the Promise object accumulates in memory.
Solution:
// 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.


Chat on WhatsApp
LinkedIn Logo Chat on LinkedIn