Introduction
Memory leaks in React often occur when side effects are not properly cleaned up inside the useEffect hook. This happens with timers, subscriptions, event listeners, or async requests that remain active even after a component unmounts. Over time, these leaks degrade performance and cause UI issues. This guide explains why leaks occur, how to prevent them, and best practices for cleanup in React functional components.
Conceptual Background
React’s useEffect hook runs side effects after a render. Side effects include:
Fetching data
Adding event listeners
Starting timers or intervals
Subscribing to WebSockets
When a component unmounts or re-renders, any unfinished side effects may continue to run. If not cleaned up, they cause memory leaks by holding references to unused state or DOM elements.
React provides a solution: return a cleanup function inside useEffect . This ensures that any active effect is disposed of before the component is unmounted.
Step-by-Step Walkthrough
1. Basic Cleanup with useEffect
import { useEffect } from "react";
function TimerComponent() {
useEffect(() => {
const timer = setInterval(() => {
console.log("Running timer...");
}, 1000);
// Cleanup function
return () => {
clearInterval(timer);
};
}, []);
return <h2>Timer running…</h2>;
}
Explanation
setIntervalstarts when the component mounts.Cleanup (
clearInterval) runs when it unmounts, preventing leaks.
2. Cleaning Event Listeners
import { useEffect } from "react";
function WindowResizeLogger() {
useEffect(() => {
const handleResize = () => console.log("Resized to", window.innerWidth);
window.addEventListener("resize", handleResize);
// Cleanup
return () => window.removeEventListener("resize", handleResize);
}, []);
return <h2>Resize the window</h2>;
}
Without cleanup, every render adds a new listener, leading to memory leaks.
3. Handling Async Calls in useEffect
Async requests may resolve after a component unmounts. Prevent leaks with an abort controller.
import { useEffect, useState } from "react";
function DataFetcher() {
const [data, setData] = useState(null);
useEffect(() => {
const controller = new AbortController();
fetch("https://jsonplaceholder.typicode.com/posts/1", {
signal: controller.signal,
})
.then((res) => res.json())
.then((json) => setData(json))
.catch((err) => {
if (err.name !== "AbortError") {
console.error("Fetch error:", err);
}
});
return () => controller.abort(); // cancel fetch on unmount
}, []);
return <pre>{JSON.stringify(data, null, 2)}</pre>;
}
Join the conversation! Your thoughts help the community grow.