Essential Concepts
Understand the fundamental concepts that make TanStack Query powerful and easy to use.Query Keys
Query keys are the foundation of TanStack Query’s caching system. They uniquely identify each query in your application.Basic Keys
The simplest query key is an array with a single string:Keys with Variables
Include variables in your query key to create unique cache entries:Complex Keys
Query keys can include objects for more complex scenarios:Object keys are sorted automatically, so
{a: 1, b: 2} and {b: 2, a: 1} produce the same cache key.Query Functions
The query function is where you fetch your data. It must return a Promise that resolves to data or throws an error.Basic Query Function
Using Query Key in Function
The query function receives a context object with the query key:Signal for Cancellation
Use the AbortSignal for request cancellation:Stale Time vs Cache Time
Understanding these two concepts is crucial for effective caching:Stale Time
staleTime determines how long data is considered fresh:
- Fresh data: Won’t refetch automatically
- Stale data: Will refetch in the background when conditions trigger it
- Default:
0(immediately stale)
Cache Time (gcTime)
gcTime (garbage collection time) determines how long unused data stays in cache:
- Data remains in cache after all observers unmount
- After
gcTimeexpires, data is garbage collected - Default:
5 minutes
staleTime affects when queries refetch. gcTime affects when cache entries are removed from memory.Query Status
Queries can be in one of several states:Status
pending- No cached data and query is currently fetchingerror- Query encountered an errorsuccess- Query succeeded and data is available
Fetch Status
fetching- Query function is executingpaused- Query wants to fetch but is paused (offline)idle- Query is not fetching
Mutations
While queries fetch data, mutations modify data on the server:Mutation Status
Optimistic Updates
Update the UI immediately before the server responds:Dependent Queries
Some queries depend on data from other queries:Use the
enabled option to control when queries execute based on other data availability.Query Invalidation
Invalidate queries to mark them as stale and trigger refetches:Prefetching
Fetch data before it’s needed for better user experience:Next Steps
TypeScript
Learn how to use TanStack Query with TypeScript
DevTools
Set up DevTools to visualize your queries