Quick Start
This guide walks you through building your first application with TanStack Query. We’ll use React in this example, but the concepts apply to all supported frameworks.Prerequisites
Before you begin, make sure you have:- Node.js installed (version 16 or higher recommended)
- A React application set up (using Vite, Create React App, or Next.js)
- TanStack Query installed (see Installation)
Setup
Create a QueryClient
The
QueryClient manages your queries and cache. Create one at the root of your application:Wrap your app with QueryClientProvider
The
QueryClientProvider makes the QueryClient available to your entire component tree:Create your first query
Use the
useQuery hook to fetch and cache data. You need:- A unique
queryKeyto identify the query - A
queryFnthat returns a promise
TanStack Query automatically handles:
- Caching the response
- Deduplicating identical requests
- Refetching when the window regains focus
- Retrying failed requests
- Updating loading and error states
Complete Example
Here’s the complete working example:Understanding the Query Result
TheuseQuery hook returns an object with several useful properties:
data- The successfully fetched data (undefined until the query succeeds)error- The error object if the query failed (null if successful)isPending-trueif the query is currently fetching for the first timeisError-trueif the query encountered an errorisSuccess-trueif the query was successfulisFetching-truewhenever the query is fetching (including background refetches)refetch- A function to manually trigger a refetch
Query Keys
Query keys uniquely identify your queries. They can be:When any value in the query key changes, TanStack Query automatically refetches the data. This makes dependent queries trivial to implement.
What Happens Automatically?
With zero configuration, TanStack Query:- Caches your data in memory
- Deduplicates identical requests that happen simultaneously
- Refetches data when the window regains focus
- Refetches data when the network reconnects
- Retries failed requests with exponential backoff
- Marks data as stale after a configurable time period
- Garbage collects unused cache data
Next Steps
Now that you’ve built your first query, explore more advanced features:Query Options
Configure caching, refetching, and retry behavior
Mutations
Learn how to create, update, and delete data
Query Invalidation
Keep your data fresh after mutations
Pagination
Implement paginated and infinite scroll queries
Framework-Specific Examples
While this guide uses React, the concepts are identical across frameworks. The main differences are:- Vue: Use
useQueryfrom@tanstack/vue-querywith Vue’s Composition API - Solid: Use
createQueryfrom@tanstack/solid-queryas a primitive - Svelte: Use
createQueryfrom@tanstack/svelte-querywith Svelte’s reactive syntax - Angular: Use
injectQueryfrom@tanstack/angular-query-experimentalwith Signals