)
}
```
## Suspense Integration
```tsx
import { useSuspenseQuery, useSuspenseInfiniteQuery } from '@tanstack/react-query'
// Component will suspend until data is loaded
function TodoList() {
const { data } = useSuspenseQuery({
queryKey: ['todos'],
queryFn: fetchTodos,
})
// data is guaranteed to be defined here
return
{data.map(todo =>
{todo.title}
)}
}
// Wrap with Suspense boundary
function App() {
return (
}>
}>
)
}
// Multiple suspense queries (fetch in parallel)
function Dashboard() {
const [{ data: users }, { data: projects }] = useSuspenseQueries({
queries: [
{ queryKey: ['users'], queryFn: fetchUsers },
{ queryKey: ['projects'], queryFn: fetchProjects },
],
})
}
```
## Prefetching
```tsx
const queryClient = useQueryClient()
// Prefetch on hover
function TodoLink({ todoId }) {
const prefetch = () => {
queryClient.prefetchQuery({
queryKey: ['todo', todoId],
queryFn: () => fetchTodo(todoId),
staleTime: 5000, // Only prefetch if data older than 5s
})
}
return (
Todo {todoId}
)
}
// Prefetch in route loader (TanStack Router integration)
export const Route = createFileRoute('/todos/$todoId')({
loader: ({ context: { queryClient }, params: { todoId } }) =>
queryClient.ensureQueryData(todoQueryOptions(todoId)),
})
// Prefetch infinite queries
queryClient.prefetchInfiniteQuery({
queryKey: ['projects'],
queryFn: fetchProjects,
initialPageParam: 0,
pages: 3, // Prefetch first 3 pages
})
```
## SSR & Hydration
### Server-Side Prefetching
```tsx
// Server component or loader
import { dehydrate, HydrationBoundary, QueryClient } from '@tanstack/react-query'
async function getServerSideProps() {
const queryClient = new QueryClient()
await queryClient.prefetchQuery({
queryKey: ['todos'],
queryFn: fetchTodos,
})
return {
props: {
dehydratedState: dehydrate(queryClient),
},
}
}
function Page({ dehydratedState }) {
return (
)
}
```
### Streaming SSR (React Server Components)
```tsx
import { dehydrate, HydrationBoundary } from '@tanstack/react-query'
import { makeQueryClient } from './query-client'
export default async function Page() {
const queryClient = makeQueryClient()
// Prefetch on server
await queryClient.prefetchQuery({
queryKey: ['todos'],
queryFn: fetchTodos,
})
return (
)
}
```
## QueryClient API
```tsx
const queryClient = useQueryClient()
// Get cached data
queryClient.getQueryData(['todos'])
// Set cached data
queryClient.setQueryData(['todos'], updatedTodos)
queryClient.setQueryData(['todos'], (old) => [...old, newTodo])
// Get query state
queryClient.getQueryState(['todos'])
// Check if fetching
queryClient.isFetching({ queryKey: ['todos'] })
queryClient.isMutating()
// Cancel queries
queryClient.cancelQueries({ queryKey: ['todos'] })
// Invalidate (marks stale, refetches active)
queryClient.invalidateQueries({ queryKey: ['todos'] })
// Refetch (force refetch even if fresh)
queryClient.refetchQueries({ queryKey: ['todos'] })
// Remove from cache
queryClient.removeQueries({ queryKey: ['todos'] })
// Reset to initial state
queryClient.resetQueries({ queryKey: ['todos'] })
// Clear entire cache
queryClient.clear()
// Prefetch
queryClient.prefetchQuery({ queryKey: ['todos'], queryFn: fetchTodos })
queryClient.ensureQueryData({ queryKey: ['todos'], queryFn: fetchTodos })
// Get/set defaults
queryClient.setQueryDefaults(['todos'], { staleTime: 10000 })
queryClient.getQueryDefaults(['todos'])
queryClient.setMutationDefaults(['addTodo'], { mutationFn: addTodo })
```
## Testing
```tsx
import { renderHook, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
function createWrapper() {
const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: false, // Don't retry in tests
gcTime: Infinity, // Prevent garbage collection during tests
},
},
})
return ({ children }) => (
{children}
)
}
test('fetches todos', async () => {
const { result } = renderHook(() => useQuery({
queryKey: ['todos'],
queryFn: fetchTodos,
}), { wrapper: createWrapper() })
await waitFor(() => expect(result.current.isSuccess).toBe(true))
expect(result.current.data).toEqual(expectedTodos)
})
// Mock with setQueryData for component tests
test('renders todos', () => {
const queryClient = new QueryClient()
queryClient.setQueryData(['todos'], mockTodos)
render(
)
expect(screen.getByText('Todo 1')).toBeInTheDocument()
})
```
## TypeScript Patterns
### Typing Query Functions
```tsx
interface Todo {
id: number
title: string
completed: boolean
}
// Type is inferred from queryFn return type
const { data } = useQuery({
queryKey: ['todos'],
queryFn: async (): Promise => {
const res = await fetch('/api/todos')
return res.json()
},
})
// data: Todo[] | undefined
// With select
const { data } = useQuery({
queryKey: ['todos'],
queryFn: fetchTodos,
select: (data): string[] => data.map(t => t.title),
})
// data: string[] | undefined
```
### Typing Errors
```tsx
// Default error type is Error
const { error } = useQuery({
queryKey: ['todos'],
queryFn: fetchTodos,
})
// Or register globally
declare module '@tanstack/react-query' {
interface Register {
defaultError: AxiosError
}
}
```
### Query Options Pattern (Recommended)
```tsx
import { queryOptions, infiniteQueryOptions } from '@tanstack/react-query'
export const todosOptions = queryOptions({
queryKey: ['todos'] as const,
queryFn: fetchTodos,
staleTime: 5000,
})
export const todoOptions = (id: string) =>
queryOptions({
queryKey: ['todos', id] as const,
queryFn: () => fetchTodo(id),
enabled: !!id,
})
// Full type inference everywhere
const { data } = useQuery(todosOptions)
const { data } = useSuspenseQuery(todoOptions('123'))
await queryClient.ensureQueryData(todosOptions)
queryClient.invalidateQueries({ queryKey: todosOptions.queryKey })
```
## Advanced Patterns
### Window Focus Refetching
```tsx
// Disable globally
const queryClient = new QueryClient({
defaultOptions: {
queries: { refetchOnWindowFocus: false },
},
})
// Custom focus manager
import { focusManager } from '@tanstack/react-query'
// For React Native
focusManager.setEventListener((handleFocus) => {
const subscription = AppState.addEventListener('change', (state) => {
handleFocus(state === 'active')
})
return () => subscription.remove()
})
```
### Network Mode
```tsx
useQuery({
queryKey: ['todos'],
queryFn: fetchTodos,
// 'online' (default): only fetch when online
// 'always': always fetch (useful for local-first)
// 'offlineFirst': try fetch, use cache if offline
networkMode: 'offlineFirst',
})
```
### Query Cancellation
```tsx
useQuery({
queryKey: ['todos'],
queryFn: async ({ signal }) => {
// signal is AbortSignal - automatically cancelled on unmount or key change
const res = await fetch('/api/todos', { signal })
return res.json()
},
})
// Manual cancellation
queryClient.cancelQueries({ queryKey: ['todos'] })
```
### Persistence
```tsx
import { persistQueryClient } from '@tanstack/react-query-persist-client'
import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister'
const persister = createSyncStoragePersister({
storage: window.localStorage,
})
persistQueryClient({
queryClient,
persister,
maxAge: 1000 * 60 * 60 * 24, // 24 hours
})
```
## Best Practices
1. **Use `queryOptions` helper** for type-safe, reusable query configurations
2. **Structure query keys hierarchically** for granular invalidation
3. **Set appropriate `staleTime`** - 0 means always refetch on mount (default), increase for less dynamic data
4. **Use `placeholderData`** (not `initialData`) for keeping previous page data during pagination
5. **Prefer `useSuspenseQuery`** when using Suspense boundaries for cleaner component code
6. **Use `enabled`** for dependent queries, not conditional hook calls
7. **Always invalidate after mutations** - don't rely solely on optimistic updates
8. **Cancel queries in `onMutate`** before optimistic updates to prevent race conditions
9. **Use `ensureQueryData`** in route loaders instead of `prefetchQuery` for immediate access
10. **Set `retry: false` in tests** to avoid timeout issues
11. **Don't destructure the query result** if you need to pass it around (breaks reactivity)
12. **Use `select`** for derived data instead of transforming in the component
13. **Keep query functions pure** - they should only fetch, not cause side effects
14. **Use `gcTime: Infinity`** in tests to prevent cache cleanup during assertions
## Common Pitfalls
- Using `initialData` when you mean `placeholderData` (initialData counts as "fresh" data)
- Not providing `initialPageParam` for infinite queries (required in v5)
- Calling hooks conditionally (violates React rules)
- Not cancelling queries before optimistic updates (race conditions)
- Setting `staleTime` higher than `gcTime` (data gets garbage collected while "fresh")
- Forgetting to wrap tests with `QueryClientProvider`
- Using same `QueryClient` instance across tests (shared state)
- Not awaiting `invalidateQueries` in mutation callbacks when order matters