tanstack-query-patternslisted
Install: claude install-skill AppVerk/av-marketplace
# TanStack Query Patterns — Server State
## Overview
TanStack Query patterns for server state:
- `queryOptions` helper pattern
- Query key factories
- API service layer (pure functions)
- Axios interceptors
- Mutations with optimistic updates
- Global error handling
- Error boundaries
- Suspense integration
---
## Hard Rules
<HARD-RULES>
These rules are NON-NEGOTIABLE. Violating any of them is a bug.
- ALWAYS use `queryOptions` helper to define queries — single source of truth for queryKey + queryFn
- ALWAYS use query key factories — one source of truth per domain
- NEVER cache API responses in Zustand — TanStack Query IS the server state cache
- NEVER use `onSuccess` / `onError` on `useQuery` — removed in v5; use `QueryCache`/`MutationCache` callbacks
- ALWAYS set `retry: false` and `gcTime: 0` in test QueryClient
- ALWAYS invalidate after mutation — never manual cache update unless optimistic
- NEVER use raw `useEffect` + `fetch` for API calls — TanStack Query for EVERY API call
- ALWAYS define API functions as pure functions in the service layer
- ALWAYS use Axios with centralized interceptors for auth + error handling
</HARD-RULES>
---
## API Service Layer
### Axios Client
```typescript
// src/lib/api-client.ts
import axios from 'axios';
import type { AxiosError, InternalAxiosRequestConfig, AxiosResponse } from 'axios';
const API_BASE_URL = import.meta.env.VITE_API_URL ?? 'http://localhost:3000/api';
export const apiClient = axios.create({
baseURL: API_BASE