Frontend
TanStack Query
A library for server data: queries, caching, background refetching and mutations.
What it is
Tanner Linsley created TanStack Query (formerly React Query) in 2019. It treats server data as its own kind of state: it must be fetched, cached, refreshed and synced, not stored by hand in a global store.
You describe a query with a key and a fetch function, and the library caches the result, dedupes identical requests, retries failures and refreshes stale data in the background. For changes there are mutations with cache invalidation and optimistic updates.
There are adapters for React, Vue, Svelte, Solid and Angular. The library shortens code and removes many useEffect data loads.
Use it when
- The app talks to REST or GraphQL APIs a lot.
- You need cache, retries, pagination and infinite scroll without hand-rolling them.
- You want server data out of Redux or Context.
Avoid it when
- Only local UI state (an open modal, a form value).
- A meta-framework already gives data loading that is enough, such as Next.js server components for simple cases.
Key concepts
- Query key
- An array that identifies the query. Caching and invalidation work by it.
- staleTime and gcTime
- How long data counts as fresh and how long it stays cached with no subscribers.
- Mutation
- A request that changes data on the server; the cache is invalidated afterwards.
- Background refetch
- Refresh on tab focus, network reconnect or an interval.
- Optimistic updates
- Show the result of an action instantly and roll back if the server fails.
Example
Interview questions
1. What is queryKey for?
A unique identifier of the data in the cache. The library uses it to find a cached result, dedupe requests and know what to invalidate after a mutation. Query variables (id, filters) go into the key.
2. How do staleTime and gcTime differ?
staleTimesets how long data counts as fresh with no refetch.gcTimesets how long inactive data stays in cache before removal.3. How do you refresh a list after creating an item?
In the mutation's
onSuccesscallqueryClient.invalidateQueries({ queryKey: ['items'] })and the list refetches. Or change the cache optimistically.4. Why is TanStack Query better than useEffect + useState?
It gives caching, deduplication, retries, loading and error states, background refresh and pagination without hand-written code, and avoids request races.
Interview questions from the bank
Related technologies
- ReactA library for building interfaces from components: UI as a function of state.
- ReduxA predictable state container: a single store, changes only through actions and reducers.
- GraphQLA query language and API specification where the client states exactly which fields it needs.
- TypeScriptA superset of JavaScript with static types that compiles to plain JS.
Logos belong to their owners and are used for identification only. Icons: Simple Icons (CC0), Devicon (MIT).