tezvyn:

Cancelling fetch with AbortController

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

lifecycle-aware async cleanup.

OUTLINE

pass an AbortController signal to fetch and call abort() on unmount to avoid wasted work, race conditions, and state updates on gone components.

RED FLAG

ignoring cleanup and setting state after unmount.

WHAT THIS TESTS Whether you connect asynchronous requests to the component lifecycle and understand the concrete harms of orphaned fetches, plus the correct AbortController mechanics.

A GOOD ANSWER COVERS When a screen unmounts mid-fetch, the request keeps running and its callback may set state on a component that no longer exists, wasting work and risking race conditions where an older, slower response overwrites newer data. Cancellation avoids this. With fetch you create an AbortController, pass controller.signal as the signal option, and call controller.abort() from the useEffect cleanup function. The pending fetch then rejects with an AbortError, which you should catch and ignore rather than surface as a failure. The same signal can cancel related requests, and you should also guard or replace state updates so stale responses are dropped.

COMMON WRONG ANSWERS Not cleaning up at all, treating AbortError as a genuine error shown to the user, sharing one controller across many independent requests so aborting one kills all, or relying on a mounted boolean flag instead of true cancellation, which stops the state update but not the wasted network and parsing work.

LIKELY FOLLOW-UPS How do you differentiate AbortError from a real network failure? How does this prevent the search-as-you-type race condition? How does Axios cancellation compare?

ONE CONCRETE EXAMPLE useEffect(() => { const ctrl = new AbortController(); fetch(url, { signal: ctrl.signal }).then(r => r.json()).then(setData).catch(e => { if (e.name !== 'AbortError') setError(e); }); return () => ctrl.abort(); }, [url]). On unmount or when url changes, the cleanup aborts the prior request, so a slow earlier response cannot clobber the data from the newer request, eliminating the stale-overwrite race.

Read the original → developer.mozilla.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.