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
- 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.
- 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.
- 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.
- 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.
- 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
- Query Keys Understand how query keys identify cached data: arrays, variables inside keys, deterministic hashing, hierarchical keys, key factories and common mistakes.
- Query Functions Write reliable query functions: the context object, throwing on HTTP errors, AbortSignal cancellation, default query functions and wrapping fetch or axios.
- 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.
- 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.
- 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
- Mutations with useMutation Send changes to the server with useMutation: mutationFn, mutate versus mutateAsync, isPending, error and reset, and how mutations differ from queries.
- 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.
- 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.
- 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.
- 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
- 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.
- 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.
- 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.
- 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.
- 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
- 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.
- Infinite Queries with useInfiniteQuery Learn useInfiniteQuery in TanStack Query v5: initialPageParam, getNextPageParam, fetchNextPage, hasNextPage, flattening pages and building a Load more button.
- Infinite Scroll Patterns Build infinite scrolling with useInfiniteQuery: an IntersectionObserver sentinel, bidirectional lists with fetchPreviousPage, maxPages, and search-driven feeds.
Optimistic Updates
- 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.
- 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.
- 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
- Suspense Queries Use useSuspenseQuery and useSuspenseQueries with React Suspense: no isPending checks, guaranteed data, fallbacks, nested boundaries and how to avoid request waterfalls.
- 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.
- 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.
- 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.
- 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
- 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.
- 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.
- 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
- 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.
- Project: Infinite Photo Feed Build an infinite feed with useInfiniteQuery, cursor pages, an IntersectionObserver sentinel and optimistic likes written into paginated cache pages.
- 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.
- 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.