React Query (TanStack Query): Server State Caching
Learn the interview-ready mental model, practical trade-offs, and production patterns for this web fundamentals topic.
Topic content
React Query (TanStack Query) is the standard solution for managing server state in React apps. It handles caching, request deduplication, background refetching, mutations, and optimistic updates with minimal boilerplate.
You tell it what data you want (query key). It fetches, caches, and keeps it fresh automatically. When you change data (mutation), it knows what to update or invalidate. You focus on UI; it handles the messy parts of server synchronization.
1Query Keys & Basic Usage
Query keys are the identity of your cached data. Use stable, hierarchical arrays. React Query automatically dedupes and caches based on these keys.
const { data, isLoading } = useQuery({
queryKey: ['user', userId],
queryFn: () => fetchUser(userId),
staleTime: 60_000
});2Caching Strategy (staleTime, gcTime)
staleTime controls how long data is considered fresh. gcTime controls how long inactive queries stay in memory.
3Mutations & Optimistic Updates
Use useMutation with invalidateQueries for correctness or setQueryData for instant UI. Optimistic updates provide rollback on error.
4Pagination & Infinite Scroll
Keep pagination params in query keys. Use useInfiniteQuery for infinite scrolling with getNextPageParam.
- ✓React Query is the standard for server state management
- ✓Query keys are the foundation of caching and invalidation
- ✓Use staleTime to control freshness, gcTime for memory
- ✓invalidateQueries for correctness, setQueryData for instant UX
- ✓Optimistic updates need proper rollback
- ✓Separate server state (React Query) from client state (Zustand/Context)
- ✓Always measure and tune based on real usage patterns