Fixing a Memory Leak in React by Cleaning Up useEffect
Project Overview The project is a React-based web application that fetches data from a REST API and displays it in a dynamic dashboard. Users can navigate between pages, search data, and interact with multiple components that rely on asynchronous API calls. While testing the application, I noticed that navigating away from a page during an active API request occasionally caused React warnings and unnecessary memory usage. This issue affected the application's stability and could lead to performance degradation over time. The problem was caused by an asynchronous operation continuing even after the component had been unmounted. For example, an API request initiated inside useEffect would still complete after the user navigated away, attempting to update the component's state. React would warn that a state update was attempted on an unmounted component. Before useEffect(() => { fetch("/api/users") .then((res) => res.json()) .then((data) => setUsers(data)); }, []); If the component unmounted before the request finished, the callback still attempted to update the state. After I solved the issue by using the AbortController API to cancel the request during cleanup. useEffect(() => { const controller = new AbortController(); fetch("/api/users", { signal: controller.signal, }) .then((res) => res.json()) .then((data) => setUsers(data)) .catch((err) => { if (err.name !== "AbortError") { console.error(err); } }); return () => controller.abort(); }, []); This ensures that pending requests are cancelled when the component unmounts, preventing unnecessary state updates and avoiding memory leaks. Code Prince3963 (Patel Prince) / Repositories · GitHub Prince3963 has 48 repositories available. Follow their code on GitHub. github.com My Improvements This fix focused on improving both performance and application reliability. What I improved Prevented memory leaks caused by unfinished asynchronous requests. Added proper cleanup logic inside useEffect. Eliminated React warnings about u