Query Function Basics
A query function is any function that returns a Promise:Query Function Context
Query functions receive aQueryFunctionContext object as their first argument:
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
Fromquery.ts:545-556, TanStack Query validates that data is not undefined:
Error Handling
Throwing Errors
Throw errors to indicate failure:Custom Error Objects
Throw custom error objects for better error handling:Error Dispatch
Fromquery.ts:584-600, errors are dispatched to update query state:
Request Cancellation
Using AbortSignal
Thesignal property in the context allows you to cancel requests:
How Signal Works
Fromquery.ts:430-443, the signal is lazily created:
- 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:queryClient.ts:278-291:
Query Function Types
Type Signature
Fromtypes.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
UseskipToken to skip query execution:
queryClient.ts:616-618:
Query Function Context Usage
Real-world example from the basic example (examples/react/basic/src/index.tsx:84-89):