Dev.Lib
arrow_backBack to Blogs
LEVEL_055.6June 27, 20261 min read

AbortController

Caching & Networking

Cancel in-flight fetch when component unmounts, route changes, or new search supersedes old.

Summary

Cancel in-flight fetch when component unmounts, route changes, or new search supersedes old. Pass signal to fetch; catch AbortError separately from real errors. Link abort to React effect cleanup. Without abort: setState on unmounted component and race conditions.

Code example

const controller = new AbortController();

fetch('/api/search?q=react', { signal: controller.signal })
  .then((r) => r.json())
  .catch((err) => {
    if (err.name === 'AbortError') return;
    throw err;
  });

controller.abort(); // cancels in-flight request

Key points

  • Cancel in-flight fetch when component unmounts, route changes, or new search supersedes old.
  • Pass signal to fetch; catch AbortError separately from real errors.
  • Link abort to React effect cleanup.
  • Without abort: setState on unmounted component and race conditions.

Further reading

Related concepts