React Hooks Patterns/Fetch with AbortController

Cancel stale requests on dependency change.

Section: Data Fetching Patterns

Fetch with AbortController

tsx
tsx
useEffect(() => {
  const controller = new AbortController();
  fetch(`/api/search?q=${encodeURIComponent(query)}`, { signal: controller.signal })
    .then(r => r.json())
    .then(setResults)
    .catch(err => {
      if (err.name !== 'AbortError') throw err;
    });
  return () => controller.abort();
}, [query]);
Explanation

Aborting requests is cleaner than race flags when the underlying API supports it.

Learn the surrounding workflow

Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.

Related commands

Same sheet · prioritizing Data Fetching Patterns
Track loading, error, and data state
Model async UI state explicitly.
OpenIn sheettsxsame section
Expose derived async status
Return a status object from custom data hooks.
OpenIn sheettsxsame section
Basic custom hook
Extract reusable stateful logic into a function.
OpenIn sheettsx2 tag match
Track previous value
Store the previous render’s value.
OpenIn sheettsx2 tag match
Controlled form state
Manage a form object with useState.
OpenIn sheettsx2 tag match
Custom hook with options object
Prefer options objects for extensible APIs.
OpenIn sheettsx2 tag match