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 dataUI state (modals, tabs, forms)
Cached, stale, refetchableDirectly owned by the client
Shared across componentsOften local to a component
Has loading/error statesImmediately available

Core Concepts

ConceptDescription
useQueryFetch & cache data (GET)
useMutationModify data (POST/PUT/DELETE)
queryKeyUnique cache identifier (like a URL)
queryFnThe function that fetches data
staleTimeHow long data is "fresh" before refetching
gcTimeHow long unused cache stays in memory
invalidateQueriesMark cache as stale → triggers refetch
QueryClientThe cache manager

Defaults

SettingDefaultMeaning
staleTime0Data is immediately stale (refetches on mount)
gcTime5 minUnused cache garbage-collected after 5 min
retry3Retries failed requests 3 times
refetchOnWindowFocustrueRefetches when user returns to the tab

File

  • tanstack-query.tsx — useQuery, useMutation, invalidation, optimistic updates, pagination, infinite scroll, prefetching, dependent queries