HomeReact
Chapter 16
16 — TanStack Query (React Query)
TanStack Query manages server state — data that lives on the server and needs fetching, caching, synchronizing, and updating.
Server State vs Client State
| Server State (TanStack Query) | Client State (useState/Zustand) |
|---|---|
| API responses, DB data | UI state (modals, tabs, forms) |
| Cached, stale, refetchable | Directly owned by the client |
| Shared across components | Often local to a component |
| Has loading/error states | Immediately available |
Core Concepts
| Concept | Description |
|---|---|
useQuery | Fetch & cache data (GET) |
useMutation | Modify data (POST/PUT/DELETE) |
queryKey | Unique cache identifier (like a URL) |
queryFn | The function that fetches data |
staleTime | How long data is "fresh" before refetching |
gcTime | How long unused cache stays in memory |
invalidateQueries | Mark cache as stale → triggers refetch |
QueryClient | The cache manager |
Defaults
| Setting | Default | Meaning |
|---|---|---|
staleTime | 0 | Data is immediately stale (refetches on mount) |
gcTime | 5 min | Unused cache garbage-collected after 5 min |
retry | 3 | Retries failed requests 3 times |
refetchOnWindowFocus | true | Refetches when user returns to the tab |
File
tanstack-query.tsx— useQuery, useMutation, invalidation, optimistic updates, pagination, infinite scroll, prefetching, dependent queries