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?