Canceling In-Flight Requests with Axios

Learn how to cancel in-flight requests to avoid race conditions, wasted work, and stale UI updates in React.

In dynamic interfaces like search bars or dashboards, rapid user input can trigger a cascade of network requests before previous ones complete. For instance, as a user types "React," the app might request results for "R," then "Re," and "Rea" in quick succession. Without a cancellation strategy, a race condition can occur: a slower, obsolete response might arrive after a newer one, overwriting the UI with stale data. This flood of redundant requests also wastes bandwidth and degrades application performance, leading to an inconsistent and sluggish user experience. That’s where request cancellation comes in. Instead of letting every request run to completion, we can abort unnecessary requests as soon as they’re no longer needed

Why canceling requests matters

When dealing with fast user interactions or multiple state changes, it’s easy for overlapping network requests to get out of sync. Consider two requests:

  • Request A: Triggered first, takes longer to respond.

  • Request B: Triggered second, responds faster.

Without cancellation, the late response from Request A might replace Request B’s results in the UI — creating a stale update. This kind of race condition is one of the most common and subtle bugs in real-world React apps.

React’s concurrent rendering model makes these issues even more noticeable. Components may render multiple times quickly, and we need to ensure that only the latest request’s response updates the screen.
To achieve that, we use AbortController, which gives us a signal we can pass to Axios so that we can abort old requests when starting a new one.