AbortController: Manage Memory Efficiently in React
How to use AbortController to cancel fetch requests and prevent memory leaks in React components.

In modern React applications, managing memory efficiently is essential to ensure good performance. A common issue developers face is memory leaks that can occur during asynchronous fetch operations.
The AbortController is a powerful utility that helps mitigate these leaks.
The problem
When a component fires an async request and unmounts before the response arrives, the setState from a still-running promise can cause errors and hold references in memory. Result: memory leak and warnings in the console.
The solution: AbortController
AbortController lets you cancel ongoing fetch requests. Combined with useEffect cleanup, you cancel the request when the component unmounts.
import React, { useState, useEffect } from 'react';
const FetchDataComponent = () => {
const [data, setData] = useState(null);
useEffect(() => {
const controller = new AbortController();
const signal = controller.signal;
const fetchData = async () => {
try {
const response = await fetch('https://api.example.com/data', { signal });
const data = await response.json();
if (!signal.aborted) {
setData(data);
}
} catch (error) {
if (error.name !== 'AbortError') {
console.error('Fetch error:', error);
}
}
};
fetchData();
return () => {
controller.abort();
};
}, []);
return (
<div>
{data ? <pre>{JSON.stringify(data, null, 2)}</pre> : 'Loading...'}
</div>
);
};
How it works
- Create an
AbortControllerinstance and grab itssignal. - Pass the
signaltofetchvia the second argument. - In the
useEffectcleanup, callcontroller.abort(). - The
fetchis interrupted, throwing anAbortErrorwe handle incatch.
Conclusion
Adopting AbortController in your React project helps manage async operations efficiently, prevents memory leaks, and ensures a smoother UX.
Learn more at MDN — AbortController.
May 6, 2023 · Brazil