TG
react·javascript·performance·2 min read

AbortController: Manage Memory Efficiently in React

How to use AbortController to cancel fetch requests and prevent memory leaks in React components.

AbortController: Manage Memory Efficiently in React

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

  1. Create an AbortController instance and grab its signal.
  2. Pass the signal to fetch via the second argument.
  3. In the useEffect cleanup, call controller.abort().
  4. The fetch is interrupted, throwing an AbortError we handle in catch.

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.

Thiago Marinho

May 6, 2023 · Brazil