AbortController in Fetch API with React
When working with API calls in React, we often need to handle scenarios where requests must be canceled, whether due to fast component changes or multiple concurrent requests that end up being unnecessary. This is where AbortController comes in!
It allows you to cancel requests made with fetch(), improving performance and preventing issues like memory leaks when users navigate quickly between different components.
Here's a basic example of how to use it with React and TypeScript:
import { useEffect } from 'react';
const useFetchData = (url: string) => {
useEffect(() => {
const controller = new AbortController();
const signal = controller.signal;
const fetchData = async () => {
try {
const response = await fetch(url, { signal });
if (!response.ok) throw new Error('Request failed');
const data = await response.json();
console.log(data);
} catch (error) {
if (error.name === 'AbortError') {
console.log('Request canceled');
} else {
console.error('Error:', error);
}
}
};
fetchData();
return () => {
controller.abort(); // Cancels the request when the component unmounts
};
}, [url]);
};
Tips:
This small adjustment can greatly affect your app's performance and code maintenance!
#React #TypeScript #WebDevelopment #JavaScript #APIs #Frontend
Senior Front-end Software Engineer | Mobile Developer | ReactJS | React Native | TypeScript | NodeJS
10moGreat advice
.NET Software Engineer | Full Stack Developer | C# | Angular & Blazor | Azure & AWS | Microservices Expert
10moNice content, thanks for sharing
Senior MS SQL Server DBA | Data Engineer | Azure & AWS Cloud Expert | Performance Tuning & HADR Specialist | Databricks - Azure - AWS Certified
10moInteresting
Software Engineer | Software Developer | Backend Developer | C# | .NET Core | AWS Certified | Angular
10moVery informative
Software Engineer | AI Developer | AI Agents | LLM | Langchain | LangGraph | Python | Go (golang) | NodeJS (Javascrit) | AWS | Azure | Git | Microservices | Solutions Architect
10moInsightful, thanks for sharing