Skip to main content
Query functions are the functions that actually fetch your data. They can be any function that returns a promise.

Basic Query Function

A query function must return a promise that resolves data or throws an error:
Query functions must throw errors instead of returning them for proper error handling.

Query Function Context

Query functions receive a context object with useful properties:

Using the Context

Query Function Patterns

Handling Errors

Query functions should throw errors for failed requests:
Do not return errors from query functions. Always throw them.

Query Function with Axios

Query Function with Fetch API

Complete example with proper error handling:

Cancellation with AbortSignal

Use the signal for request cancellation:
When a query is cancelled (e.g., component unmounts), the AbortSignal is automatically triggered.

Dependent Data in Query Functions

Extract dependencies from the query key:

Parallel Requests in Query Function

Fetch multiple resources in a single query:

Default Query Function

Set a default query function for all queries:

TypeScript Query Functions

Type-safe query functions:

Query Functions with GraphQL

Query Functions with tRPC

Paginated Query Function

Infinite Query Function

Query Function Error Types

Type errors properly:

Retry Logic in Query Functions

Query functions automatically retry based on query options:
The query function doesn’t need to implement retry logic - TanStack Query handles it automatically.

Query Function with Authentication

Transforming Data in Query Functions

Transform data in the query function for consistent structure, or use the select option for view-specific transformations.

Query Function Best Practices

1

Always Return Promises

Query functions must return a promise.
2

Throw Errors

Throw errors instead of returning them.
3

Use AbortSignal

Support cancellation with the signal.
4

Extract from Query Key

Get parameters from the query key for consistency.