Skip to content
Tutorials Center
My learning

Topics

TanStack Query Tutorial

Learn TanStack Query step by step: 38 lessons in 9 chapters with examples, quizzes, diagrams and projects.

Start learning →

of lessons completed

Getting Started

  1. 1 What Is TanStack Query? Learn what TanStack Query (React Query) does, why server state is different from client state, and how a cache of async data replaces hand-written fetch code.
  2. 2 Installing and Setting Up TanStack Query Install TanStack Query v5, create a QueryClient, wrap your React app in QueryClientProvider, set sensible default options and learn where the client should live.
  3. 3 Your First Query with useQuery Write your first useQuery call: query key, query function, data, loading and error handling, and see how much code the hook replaces compared with useEffect.
  4. 4 Query Status and Fetch Status Understand status, fetchStatus, isPending, isLoading, isFetching and isPaused in TanStack Query, and learn which flag to use for spinners, banners and offline states.
  5. 5 QueryClient and QueryClientProvider Learn what the QueryClient is, how QueryClientProvider shares it, how to set default options for every query, and the mistakes that create a fresh cache by accident.

Queries and Keys

  1. 6 Query Keys Understand how query keys identify cached data: arrays, variables inside keys, deterministic hashing, hierarchical keys, key factories and common mistakes.
  2. 7 Query Functions Write reliable query functions: the context object, throwing on HTTP errors, AbortSignal cancellation, default query functions and wrapping fetch or axios.
  3. 8 Dependent Queries and the enabled Option Run one query after another with the enabled option: chain requests, wait for user input, understand isLoading versus isPending for idle queries, and avoid waterfalls.
  4. 9 Parallel Queries and useQueries Run several queries at once with multiple useQuery calls or useQueries for a dynamic number, merge results with combine, and know how to keep requests parallel.
  5. 10 select, queryOptions and Reusable Queries Transform cached data with select, share one definition across hooks and the client with queryOptions, and learn how structural sharing limits re-renders.

Mutations

  1. 11 Mutations with useMutation Send changes to the server with useMutation: mutationFn, mutate versus mutateAsync, isPending, error and reset, and how mutations differ from queries.
  2. 12 Invalidating Queries After Mutations Keep the screen in sync after a write: invalidateQueries, key prefixes and filters, returning the promise to await the refetch, and when not to refetch.
  3. 13 Mutation Callbacks and Lifecycle Learn the mutation lifecycle: onMutate, onSuccess, onError and onSettled, their order and arguments, hook-level versus per-call callbacks, and what happens on unmount.
  4. 14 Updating the Cache from Responses Write mutation responses straight into the cache with setQueryData and setQueriesData, use functional updaters safely, and decide between writing and invalidating.
  5. 15 Mutation State, Keys and Scopes Observe mutations from anywhere with useIsMutating and useMutationState, name them with mutationKey, and run related mutations one at a time with scope.

Caching and Staleness

  1. 16 Stale Time and Garbage Collection Time The two timers that drive TanStack Query caching: staleTime decides when data needs a refresh, gcTime when unused data is deleted. Learn the lifecycle and how to tune both.
  2. 17 Refetch Triggers: Focus, Reconnect and Mount Learn which events make stale queries refetch automatically: window focus, network reconnect, component mount and interval. Tune them and simulate them with focusManager.
  3. 18 Polling and Background Refetching Keep data live with refetchInterval: fixed and dynamic intervals, stopping when a job finishes, pausing in background tabs, and when to prefer websockets.
  4. 19 Retries and Error Handling Handle failures well: default retries and back-off, custom retry rules, global error callbacks with QueryCache, throwOnError, network modes and refetch errors that keep old data.
  5. 20 Working with the Cache Directly A tour of the QueryClient cache methods: fetchQuery, ensureQueryData, refetchQueries, cancelQueries, removeQueries, resetQueries, clear, and subscribing to cache events.

Pagination and Infinite Queries

  1. 21 Paginated Queries Build page-by-page lists with TanStack Query: put the page number in the query key, keep the old page on screen with placeholderData, and prefetch the next page.
  2. 22 Infinite Queries with useInfiniteQuery Learn useInfiniteQuery in TanStack Query v5: initialPageParam, getNextPageParam, fetchNextPage, hasNextPage, flattening pages and building a Load more button.
  3. 23 Infinite Scroll Patterns Build infinite scrolling with useInfiniteQuery: an IntersectionObserver sentinel, bidirectional lists with fetchPreviousPage, maxPages, and search-driven feeds.

Optimistic Updates

  1. 24 Optimistic UI with Variables The simplest optimistic update in TanStack Query v5: render the pending mutation's variables in the UI while the request runs, with no cache writes or rollback code.
  2. 25 Optimistic Updates in the Cache Update the TanStack Query cache before the server answers: cancelQueries, snapshot with getQueryData, setQueryData in onMutate, rollback in onError and refetch in onSettled.
  3. 26 Optimistic Updates: Edge Cases Handle the hard parts of optimistic updates in TanStack Query: overlapping mutations, isMutating guards, temporary IDs, infinite list edits and serial mutation scopes.

Suspense and Prefetching

  1. 27 Suspense Queries Use useSuspenseQuery and useSuspenseQueries with React Suspense: no isPending checks, guaranteed data, fallbacks, nested boundaries and how to avoid request waterfalls.
  2. 28 Error Boundaries and Resetting Handle query errors with React error boundaries: throwOnError, QueryErrorResetBoundary, useQueryErrorResetBoundary, retry buttons and a clean split of local and global errors.
  3. 29 Prefetching and Initial Data Make screens feel instant with TanStack Query: prefetchQuery on hover, ensureQueryData, initialData from other caches, placeholderData, and when to use each one.
  4. 30 Server Rendering and Hydration Prefetch on the server and hand the cache to the browser with dehydrate and HydrationBoundary. Covers a per-request QueryClient, staleTime and the Next.js app router pattern.
  5. 31 Router Loaders and Waterfalls Start queries when navigation starts, not when components render: route loaders with ensureQueryData, parallel and dependent fetching, and how to spot and remove waterfalls.

Testing and DevTools

  1. 32 DevTools Use the TanStack Query DevTools to see every query, its status, staleness and observers, trigger refetches and errors, and read the cache while you debug.
  2. 33 Testing Queries and Mutations Test components and hooks that use TanStack Query: a fresh QueryClient per test, retry off, a wrapper, waitFor, mocking fetch or MSW, and testing loading, error and mutation flows.
  3. 34 Debugging and Production Monitoring A field guide to TanStack Query problems: stale data, extra refetches, unstable keys, re-render storms, and how to log and monitor queries and mutations in production.

Projects and Practice

  1. 35 Project: Issue Tracker Build a small issue tracker with TanStack Query: query keys for lists and details, filters, a create mutation, targeted invalidation and cache seeding.
  2. 36 Project: Infinite Photo Feed Build an infinite feed with useInfiniteQuery, cursor pages, an IntersectionObserver sentinel and optimistic likes written into paginated cache pages.
  3. 37 Project: Live Dashboard Build a live dashboard with TanStack Query: refetchInterval polling, select to derive data, dependent queries, pausing when hidden and a manual refresh button.
  4. 38 Practice: Cache Challenges Practice TanStack Query with ten exercises on keys, staleTime, invalidation, optimistic updates and pagination, each with a hint and a worked solution to compare.