Preventing Memory Leaks in React with Cleanup

🚀 7 Days of Better React – Day 6 Old Approach → Better Approach While working with API calls, I noticed something risky. A request was still resolving even after the component unmounted. This can lead to memory leaks and unexpected state updates. ❌ Old approach: useEffect(() => { fetchData().then(data => { setData(data); }); }, []); If the component unmounts before the request finishes, it may try to update state on an unmounted component. ✅ Better approach (Cleanup inside useEffect): useEffect(() => { let isMounted = true; fetchData().then(data => { if (isMounted) { setData(data); } }); return () => { isMounted = false; }; }, []); Now state updates only happen if the component is still mounted. Handling cleanup properly isn’t optional. It’s part of writing safe React code. Small protection. Big stability. #reactjs #frontenddeveloper #javascript #cleanCode #webdevelopment

  • text

Good attempt but its still incorrect instead use abort controller useEffect(() => {  const controller = new AbortController();  const signal = controller.signal;  fetchData({ signal })   .then(data => {    setData(data);   })   .catch(error => {    // When a request is aborted, it throws an AbortError.    // You should catch it so it doesn't pollute your console.    if (error.name === 'AbortError') {     console.log('Fetch aborted');    } else {     console.error('Fetch error:', error);    }   });  return () => {   // This cancels the network request immediately on unmount   controller.abort();  }; }, []);

There are a few points to consider. Today, this is client-side only, but with Server Components it’s important to separate data fetching from client-side–only hooks. Even if it’s a SPA without SSR, as mentioned above, it’s still important to use an AbortController to cancel previous requests and avoid race conditions. Another point that is cool is to use libraries like React Query, which handle all of this for you when implemented correctly.

Like
Reply

You don't do it like that. You use abortcontroller to abort the api call in the return function.

Handling cleanup like this is underrated it’s those small details that prevent real production bugs.

this is not the right way to do this. use abortController to abort the request once the component unmount

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories