React Course
React
/
Advanced

AbortController

Definition

AbortController is a browser API that allows you to abort (cancel) one or more Web requests (like `fetch` or `axios`) as and when desired.

Explain Like I'm New

Imagine ordering a pizza. While it's cooking, you change your mind and decide to go out to eat instead. If you don't call the restaurant to cancel, the pizza delivery guy will still show up at your empty house and get confused. AbortController is how you call the API to cancel the order so the data doesn't arrive after your component has unmounted.

Real World Example

A user is typing in an autocomplete search bar. They type "A", which fires a fetch. They immediately type "P", firing a second fetch. You use AbortController to cancel the "A" fetch so that if the "A" fetch takes longer to return than the "P" fetch, it doesn't overwrite the correct "P" results.

Common Use Cases

  • Search autocomplete fields
  • Preventing "state update on an unmounted component" memory leak warnings
  • Canceling large file downloads

Interactive Example

import React, { useState, useEffect } from "react";

export default function SearchWithAbort() {
  const [query, setQuery] = useState("");
  const [results, setResults] = useState([]);

  useEffect(() => {
    if (query === "") {
      setResults([]);
      return;
    }

    // 1. Create the controller
    const controller = new AbortController();

    fetch(`https://jsonplaceholder.typicode.com/posts?q=${query}`, {
      // 2. Connect the signal to the fetch request
      signal: controller.signal
    })
    .then(res => res.json())
    .then(data => setResults(data))
    .catch(err => {
      // 3. Handle the deliberate abort safely
      if (err.name === "AbortError") {
        console.log("Fetch aborted successfully for query:", query);
      } else {
        console.error("Real error:", err);
      }
    });

    // 4. CLEANUP: If the user types a new letter before this fetch finishes, 
    // React runs this cleanup, cancelling the old fetch!
    return () => {
      controller.abort();
    };
  }, [query]); // Runs every time query changes

  return (
    <div className="p-4 border">
      <h3>Type fast and check the console!</h3>
      <input 
        value={query} 
        onChange={e => setQuery(e.target.value)} 
        placeholder="Search posts..."
        className="border p-2 w-full"
      />
      <ul className="mt-2 text-sm text-gray-600">
        {results.slice(0, 3).map(post => <li key={post.id}>{post.title}</li>)}
      </ul>
    </div>
  );
}

Interview Questions

basic

  • What does AbortController do?
  • Why do we need to cancel API requests in React?

intermediate

  • How do you connect an AbortController to a `fetch` request?
  • How do you trigger the cancellation?

advanced

  • How do you properly catch an aborted fetch without crashing your app?
  • How do you use AbortController inside a `useEffect` cleanup function?

trick

  • Does `controller.abort()` stop the server from processing the request?

Flash Cards

Question

Does it stop the server from processing?

Click to reveal answer
Answer

No! The request has already been sent over the internet. The server is still doing the work and sending the response back. AbortController just tells the *browser* to immediately close the connection and ignore the incoming data.

Question

How do you use it in useEffect cleanup?

Click to reveal answer
Answer

You instantiate `const controller = new AbortController();` inside the effect, pass `signal: controller.signal` to `fetch()`, and return `() => controller.abort();` as the cleanup function. When the component unmounts, React runs the cleanup, cancelling the flight request.

Question

How do you catch an aborted fetch?

Click to reveal answer
Answer

When aborted, fetch throws an error with `err.name === "AbortError"`. You must specifically check for this in your catch block and do nothing (ignore it), otherwise you will accidentally show an error message to the user.