Skip to main content
Query functions are the core of how TanStack Query fetches data. They are async functions that return data or throw errors.

Query Function Basics

A query function is any function that returns a Promise:

Query Function Context

Query functions receive a QueryFunctionContext object as their first argument:
From types.ts:138-165, the full context definition:

Using the Context

Return Values

Query functions must return a Promise that resolves to data:

Data Validation

From query.ts:545-556, TanStack Query validates that data is not undefined:
Query functions must not return undefined. If your API can return undefined, return null instead or wrap it in an object.

Error Handling

Throwing Errors

Throw errors to indicate failure:

Custom Error Objects

Throw custom error objects for better error handling:

Error Dispatch

From query.ts:584-600, errors are dispatched to update query state:

Request Cancellation

Using AbortSignal

The signal property in the context allows you to cancel requests:

How Signal Works

From query.ts:430-443, the signal is lazily created:
The signal is automatically aborted when:
  • The query is cancelled
  • The component unmounts (if the signal was consumed)
  • A new fetch starts for the same query
TanStack Query only calls abort() on the signal if your query function accesses the signal property. This is an optimization to avoid unnecessary cancellations.

Manual Cancellation

You can manually cancel queries:
From queryClient.ts:278-291:

Query Function Types

Type Signature

From types.ts:96-100:

Typed Query Functions

Reusable Query Functions

Factory Pattern

Generic Fetcher

Query Function Best Practices

1. Always Handle Errors

2. Use Signal for Cancellation

3. Extract Query Key Parameters

4. Type Your Return Values

Skip Token

Use skipToken to skip query execution:
From queryClient.ts:616-618:
skipToken is a cleaner alternative to conditionally setting enabled: false when you don’t have a valid query function.

Query Function Context Usage

Real-world example from the basic example (examples/react/basic/src/index.tsx:84-89):