React Query Basics
React Query Basics covers TanStack Query server state, query keys, invalidation, useQuery versus useMutation, and QueryClient setup.
Course: React — State Management Lesson: 09
Learning objectives
Understand server state, configure TanStack Query (formerly commonly called React Query), fetch data with useQuery, perform mutations, and understand query keys.
What problem does TanStack Query solve?
Server data has concerns beyond storing a value: freshness, caching, background refetching, retries, request deduplication, invalidation, and synchronization after mutations. TanStack Query is designed to manage this server-state lifecycle.
Install:
npm install @tanstack/react-query
Configure QueryClient
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";const queryClient = new QueryClient();function App() {return (<QueryClientProvider client={queryClient}><Application /></QueryClientProvider>);}
Create the client outside the component render so it is not recreated on every render.
Fetch with useQuery
function OrdersPage() {const query = useQuery({queryKey: ["orders"],queryFn: fetchOrders});if (query.isPending) return <OrdersSkeleton />;if (query.isError) return <ErrorPanel error={query.error} />;return <OrderTable orders={query.data} />;}
The query key identifies the data. The query function retrieves it. TanStack Query manages the request lifecycle and cache according to its configuration.
Query keys must describe the data
If results depend on filters, include those filters in the key:
useQuery({queryKey: ["orders", { status, page }],queryFn: () => fetchOrders({ status, page })});
A key that omits meaningful inputs can cause different views to share an incorrect cache entry.
Mutations and invalidation
const queryClient = useQueryClient();const mutation = useMutation({mutationFn: createOrder,onSuccess: () => {queryClient.invalidateQueries({ queryKey: ["orders"] });}});
Invalidation marks matching cached data stale so it can be refetched according to query activity and configuration.
Server state vs client state
TanStack Query is not intended to replace every local state variable. Keep modal visibility and temporary form interaction in component state. Keep remote order data in the query cache. This separation gives each category an appropriate lifecycle.
Common mistakes
- Using incomplete query keys.
- Creating a new QueryClient on every render.
- Putting local UI state into the query cache.
- Assuming invalidation always means an immediate network request in every situation.
- Sharing cached data across users or tenants without appropriate key scope and cache lifecycle management.
Best practices
Use stable, complete query keys, centralize query defaults, invalidate after successful mutations, handle pending/error/empty states, and clear or isolate user-scoped cache on logout or tenant change.
Interview questions & answers
Interview preparation
5 questions grouped by difficulty — expand any card for a model answer and follow-up probe.
Beginner
1What is server state?
BeginnerModel answer
Remote data owned by the backend and synchronized into the client with caching and freshness rules.
2Difference between useQuery and useMutation?
BeginnerModel answer
useQueryreads/caches server data.useMutationperforms create/update/delete operations and can trigger invalidation.
Intermediate
3What is the purpose of a query key?
IntermediateModel answer
It uniquely identifies cached data, including every input that changes the result such as filters, ids, and tenant scope.
4Why should a QueryClient be created outside a component render?
IntermediateModel answer
Creating it during render can reset cache on each mount/render cycle; a stable client preserves cached data.
Advanced
5What does query invalidation do?
AdvancedModel answer
It marks cached queries stale so they refetch and stay consistent after mutations or external changes.
Practice
Build an orders page with status and page filters. Use query keys that include both filters, add an order mutation, and invalidate the order list after creation.