Server State with TanStack Query

Cache, deduplicate, refetch and mutate server data declaratively instead of hand-writing loading and error effects.

Intermediate · about 6 hours · difficulty 3/5

Learn first: State Management Principles, Fetch and Working with APIs

Fetching data in useEffect looks easy until you need caching, deduplication, retries, background refresh, pagination, race-condition handling and keeping the UI in sync after a mutation. TanStack Query (formerly React Query) solves all of these and is the standard tool for server state in React apps (it also supports Vue, Svelte, Solid and Angular).

Queries

useQuery({ queryKey: ["products", filters], queryFn: () => fetchProducts(filters) }) returns data, isPending, isError and more. The query key identifies cached data: components using the same key share one request and one cache entry. Change the key (for example new filters) and it fetches the new data automatically.

Freshness and caching

  • staleTime: how long data counts as fresh (no refetch). The default is 0, so tune it per query.
  • gcTime: how long unused data stays in the cache.
  • Automatic refetch on window focus and reconnect keeps screens current.

Mutations

useMutation sends writes. On success, invalidate related queries (queryClient.invalidateQueries({ queryKey: ["products"] })) so they refetch, or update the cache directly. For instant feedback, apply optimistic updates and roll back on error.

More features

Pagination and infinite scrolling (useInfiniteQuery), dependent queries (enabled), prefetching on hover and the Devtools panel. Alternatives include SWR, RTK Query, Apollo for GraphQL and framework loaders.

Good enough to move on

You can replace hand-written fetch effects with queries and mutations, pick sensible query keys and stale times, invalidate after writes and build an infinite list.

Key concepts

  • useQuery and query keys
  • staleTime, gcTime and refetching
  • useMutation and invalidation
  • Optimistic updates
  • Pagination and infinite queries
  • Dependent and parallel queries
  • Prefetching
  • SWR and RTK Query

Mini project

Build a GitHub repository explorer with TanStack Query: debounced search, paginated results, a detail view that prefetches on hover and an optimistic star/unstar toggle against a mock API.

Check yourself

Two components on the same page call useQuery with the key ['user', 42]. How many network requests are made and why?

Free resources