Skip to main content
Query cancellation allows you to abort in-flight requests when they’re no longer needed. This prevents race conditions, reduces unnecessary network usage, and improves application performance.

Automatic Cancellation

TanStack Query automatically cancels queries in several scenarios:
  • When a query becomes inactive (all observers unsubscribe)
  • When a new request starts for the same query key
  • When the component unmounts
  • When queryClient.cancelQueries() is called
The query function receives an AbortSignal in the context. Pass this signal to your fetch call to enable automatic cancellation.

Query Function Context

The query function receives a context object with an AbortSignal:
Use the signal to cancel requests:

Axios Integration

Cancel Axios requests using the signal:
Modern versions of Axios (>= 0.22.0) support the signal option natively. For older versions, use a CancelToken.

Custom Cancellation Logic

Implement custom cleanup when a query is cancelled:

Manual Query Cancellation

Cancel queries manually using queryClient.cancelQueries():
1

Import useQueryClient

Get access to the query client instance.
2

Call cancelQueries

Use query filters to cancel specific queries.
3

Handle cancellation

The query function’s signal will be aborted, triggering cleanup.

Preventing Race Conditions

Cancellation prevents race conditions when query keys change:
Without cancellation, a slow request for user “1” could complete after a fast request for user “2”, causing the UI to show incorrect data.

Cancellation with Infinite Queries

Infinite queries support cancellation for all pages:

Cancelling Before Mutations

Cancel queries before performing mutations to avoid conflicts:
Cancelling queries before optimistic updates ensures that in-flight refetches don’t overwrite your optimistic data.

Handling Cancellation Errors

Detect when a request was cancelled:

Custom Abort Controllers

Create your own abort controller for complex scenarios:
Combine TanStack Query’s signal with your own timeout logic for requests that should fail after a certain duration.

WebSocket Cancellation

Cancel WebSocket connections when queries are cancelled:

GraphQL Query Cancellation

Cancel GraphQL queries with Apollo Client or other libraries:

Retry and Cancellation

Cancellation works alongside retry logic:
If a query is cancelled during a retry, all pending retries are also cancelled. The query won’t continue retrying after cancellation.

Testing Query Cancellation

Test cancellation behavior in your components: