React Query (TanStack Query) Cheat Sheet
A reference for TanStack Query's useQuery and useMutation hooks, cache keys, and invalidation strategies for server-state management.
2 PagesIntermediateMar 2, 2026
QueryClient Setup
Providing a QueryClient to the React tree.
javascript
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';const queryClient = new QueryClient();function App() { return ( <QueryClientProvider client={queryClient}> <Todos /> </QueryClientProvider> );}
useQuery
Fetching and caching server data declaratively.
javascript
import { useQuery } from '@tanstack/react-query';function Todos() { const { data, isPending, isError, error } = useQuery({ queryKey: ['todos'], queryFn: () => fetch('/api/todos').then((res) => res.json()), staleTime: 60_000, // considered fresh for 60s }); if (isPending) return <p>Loading...</p>; if (isError) return <p>Error: {error.message}</p>; return ( <ul> {data.map((t) => ( <li key={t.id}>{t.title}</li> ))} </ul> );}
useMutation
Sending writes and invalidating related queries on success.
javascript
import { useMutation, useQueryClient } from '@tanstack/react-query';function AddTodo() { const queryClient = useQueryClient(); const mutation = useMutation({ mutationFn: (newTodo) => fetch('/api/todos', { method: 'POST', body: JSON.stringify(newTodo) }), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['todos'] }); }, }); return ( <button onClick={() => mutation.mutate({ title: 'New todo' })}> Add Todo </button> );}
Core Concepts
Key options and hooks you will reach for repeatedly.
- queryKey- an array that uniquely identifies a query, used for caching and invalidation
- queryFn- the async function that fetches and returns the data
- staleTime- how long data is considered fresh before a background refetch is triggered
- gcTime- how long unused/inactive cached data is kept before garbage collection (formerly cacheTime)
- invalidateQueries- marks matching queries as stale and triggers a refetch
- useQueryClient- hook to access the QueryClient instance for manual cache reads/writes
- enabled- option to conditionally prevent a query from running automatically
- useInfiniteQuery- hook for paginated or infinite-scroll data fetching
Pro Tip
For optimistic updates, write the new value with queryClient.setQueryData inside onMutate, save the previous value from context, and roll it back in onError -- this makes the UI feel instant without waiting for the server round-trip.
Was this cheat sheet helpful?
Explore Topics
#ReactQueryTanStackQuery#ReactQueryTanStackQueryCheatSheet#WebDevelopment#Intermediate#QueryClientSetup#UseQuery#UseMutation#CoreConcepts#Databases#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech
Professional Web Designing Services
- Responsive Websites
- E-commerce Solutions
- SEO Friendly Design
- Fast & Secure
- Support & Maintenance