Skip to main content
Get started with TanStack Query and learn the core concepts in under 5 minutes.

Prerequisites

Before you begin, make sure you have:
  • Node.js 18+ or Bun installed
  • A JavaScript or TypeScript project set up
  • Basic knowledge of React, Vue, Svelte, Solid, or Angular

Installation

Install TanStack Query for your framework:
npm install @tanstack/react-query

Basic Example

Here’s a complete working example using React Query to fetch data from an API:
1

Set up the QueryClient

Create a QueryClient instance and wrap your app with QueryClientProvider:
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'

const queryClient = new QueryClient()

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <YourApp />
    </QueryClientProvider>
  )
}
2

Use the useQuery hook

Fetch data using the useQuery hook:
import { useQuery } from '@tanstack/react-query'

function Example() {
  const { isPending, error, data } = useQuery({
    queryKey: ['repoData'],
    queryFn: async () => {
      const response = await fetch(
        'https://api.github.com/repos/TanStack/query'
      )
      return await response.json()
    },
  })

  if (isPending) return 'Loading...'
  
  if (error) return 'An error has occurred: ' + error.message

  return (
    <div>
      <h1>{data.full_name}</h1>
      <p>{data.description}</p>
      <strong>👀 {data.subscribers_count}</strong>{' '}
      <strong>{data.stargazers_count}</strong>{' '}
      <strong>🍴 {data.forks_count}</strong>
    </div>
  )
}
3

Understand what's happening

Query Key: ['repoData'] is a unique identifier for this query. TanStack Query uses it for caching.Query Function: The async function that fetches your data. It can be any async operation.Query States:
  • isPending: true when the query is loading for the first time
  • error: Contains error object if the query fails
  • data: Contains the fetched data when successful
  • isFetching: true whenever data is being fetched (including background refetches)

Key Features

Automatic Caching

TanStack Query automatically caches your data. If you navigate away and come back, the cached data is shown instantly while fresh data is fetched in the background.
// Both components use the same query key, so they share the cache
function ComponentA() {
  const { data } = useQuery({ queryKey: ['todos'], queryFn: fetchTodos })
  // ...
}

function ComponentB() {
  const { data } = useQuery({ queryKey: ['todos'], queryFn: fetchTodos })
  // Gets the same cached data instantly!
}

Automatic Refetching

Queries automatically refetch in the background when:
  • The window regains focus
  • The network reconnects
  • A configured refetch interval elapses
You can customize this behavior with options like staleTime, refetchOnWindowFocus, and refetchInterval.

Mutations

Use useMutation to modify data on your server:
import { useMutation, useQueryClient } from '@tanstack/react-query'

function AddTodo() {
  const queryClient = useQueryClient()
  
  const mutation = useMutation({
    mutationFn: (newTodo) => {
      return fetch('/api/todos', {
        method: 'POST',
        body: JSON.stringify(newTodo),
      })
    },
    onSuccess: () => {
      // Invalidate and refetch
      queryClient.invalidateQueries({ queryKey: ['todos'] })
    },
  })

  return (
    <button onClick={() => mutation.mutate({ title: 'New Todo' })}>
      Add Todo
    </button>
  )
}

Configuration Options

Customize query behavior with options:
const { data } = useQuery({
  queryKey: ['todos'],
  queryFn: fetchTodos,
  staleTime: 5 * 60 * 1000, // Data is fresh for 5 minutes
  gcTime: 10 * 60 * 1000,   // Cache kept for 10 minutes
  retry: 3,                  // Retry failed requests 3 times
  refetchOnWindowFocus: true, // Refetch when window regains focus
})

Next Steps

Essential Concepts

Learn about query keys, query functions, and caching strategies

Framework Guides

Deep dive into framework-specific usage and patterns

TypeScript

Learn how to use TanStack Query with TypeScript for full type safety

DevTools

Set up the DevTools to debug and inspect your queries

Build docs developers (and LLMs) love