AbortController in Fetch API with React

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:

  1. Always use AbortController in asynchronous requests that may be interrupted, especially in components that make fetches during short lifecycle phases.
  2. It helps prevent unwanted errors when users quickly switch between pages or when multiple requests are made simultaneously.
  3. As shown in the example above, You can easily integrate it into custom hooks.

This small adjustment can greatly affect your app's performance and code maintenance!

#React #TypeScript #WebDevelopment #JavaScript #APIs #Frontend

Felipe Dumont

Senior Front-end Software Engineer | Mobile Developer | ReactJS | React Native | TypeScript | NodeJS

10mo

Great advice

Like
Reply
Ezequiel Cardoso

.NET Software Engineer | Full Stack Developer | C# | Angular & Blazor | Azure & AWS | Microservices Expert

10mo

Nice content, thanks for sharing

Like
Reply
Rafael Rampineli

Senior MS SQL Server DBA | Data Engineer | Azure & AWS Cloud Expert | Performance Tuning & HADR Specialist | Databricks - Azure - AWS Certified

10mo

Interesting

Like
Reply
Arilson Silva

Software Engineer | Software Developer | Backend Developer | C# | .NET Core | AWS Certified | Angular

10mo

Very informative

Like
Reply
Vagner Nascimento

Software Engineer | AI Developer | AI Agents | LLM | Langchain | LangGraph | Python | Go (golang) | NodeJS (Javascrit) | AWS | Azure | Git | Microservices | Solutions Architect

10mo

Insightful, thanks for sharing

Like
Reply

To view or add a comment, sign in

Others also viewed

Explore topics