TanStack Query: A Comprehensive Guide
Table of Contents
Part I: Foundations
-
Introduction to TanStack Query
1.1 History and Evolution
1.2 Core Philosophy and Design Principles
1.3 Comparison with Other Data Fetching Solutions
1.4 The TanStack Ecosystem
-
Core Concepts
2.1 Queries vs. Mutations
2.2 Query Keys and Their Importance
2.3 Query Functions
2.4 Query Lifecycle
2.5 Stale-While-Revalidate Pattern
2.6 Cache Management
-
Setting Up TanStack Query
3.1 Installation and Basic Configuration
3.2 Query Client Setup
3.3 Provider Configuration
3.4 DevTools Integration
3.5 TypeScript Integration
Part II: Basic Usage
4. Queries in Depth
4.1 Creating Basic Queries
4.2 Query Options and Configuration
4.3 Query Status and Data Handling
4.4 Error Handling
4.5 Loading States
4.6 Dependent Queries
4.7 Parallel Queries
-
Mutations in Depth
5.1 Creating Basic Mutations
5.2 Mutation Options and Configuration
5.3 Optimistic Updates
5.4 Mutation Responses
5.5 Error Handling
5.6 Invalidation Strategies
5.7 Mutation Side Effects
-
Query Invalidation and Refetching
6.1 Manual Invalidation
6.2 Automatic Invalidation
6.3 Refetching Strategies
6.4 Background Refetching
6.5 Window Focus Refetching
6.6 Polling and Intervals
Part III: Advanced Concepts
7. Cache Management
7.1 Cache Structure and Organization
7.2 Cache Time vs. Stale Time
7.3 Custom Cache Policies
7.4 Garbage Collection
7.5 Persistence Strategies
7.6 Cache Serialization
-
Query Prefetching and Initial Data
8.1 Prefetching Strategies
8.2 Initial Data Options
8.3 Placeholder Data
8.4 Hydration Techniques
8.5 Dehydration Techniques
8.6 Server-Side Rendering Integration
-
Pagination and Infinite Queries
9.1 Offset-based Pagination
9.2 Cursor-based Pagination
9.3 Infinite Queries
9.4 Virtual Lists with Infinite Queries
9.5 Prefetching Pages
9.6 Managing Pagination State
Part IV: Specialized Use Cases
10. Server-Side Rendering
10.1 SSR Architecture with TanStack Query
10.2 Hydration Process
10.3 Dehydration Process
10.4 Next.js Integration
10.5 Remix Integration
10.6 Other Frameworks
-
Real-time Data and Subscriptions
11.1 WebSocket Integration
11.2 Server-Sent Events
11.3 Polling Strategies
11.4 Real-time Updates with Mutations
11.5 Optimistic UI with Real-time Data
-
Testing TanStack Query
12.1 Unit Testing Queries
12.2 Integration Testing
12.3 Mocking the Query Client
12.4 Testing Mutations
12.5 Testing Cache Behavior
12.6 Testing with React Testing Library
Part V: Ecosystem and Extensions
13. TanStack Query Ecosystem
13.1 React Query
13.2 Vue Query
13.3 Svelte Query
13.4 Solid Query
13.5 Angular Query
13.6 Cross-framework Patterns
-
Plugins and Extensions
14.1 Persistence Plugins
14.2 Custom Hooks and Utilities
14.3 Offline Support
14.4 Authentication Integration
14.5 Form Integration
14.6 State Management Integration
-
Performance Optimization
15.1 Query Optimization Strategies
15.2 Selective Rendering
15.3 Memoization Techniques
15.4 Network Optimization
15.5 Bundle Size Considerations
15.6 Memory Management
Part VI: Advanced Patterns and Best Practices
16. Advanced Patterns
16.1 Custom Hooks Composition
16.2 Query Orchestration
16.3 Suspense Integration
16.4 Error Boundaries
16.5 Render-as-You-Fetch Pattern
16.6 Resource Caching
-
Best Practices and Anti-patterns
17.1 Query Key Management
17.2 Structuring Query Functions
17.3 Error Handling Strategies
17.4 Performance Considerations
17.5 Common Anti-patterns
17.6 Migration Strategies
-
Case Studies and Real-world Applications
18.1 E-commerce Applications
18.2 Dashboard Applications
18.3 Social Media Applications
18.4 Enterprise Applications
18.5 Mobile-first Applications
18.6 Lessons Learned
Part VII: Future Directions and Conclusion
19. Future of TanStack Query
19.1 Upcoming Features
19.2 Experimental APIs
19.3 Community Roadmap
19.4 Integration with Emerging Technologies
19.5 Potential Challenges and Solutions
- Conclusion
20.1 Summary of Key Concepts
20.2 When to Use TanStack Query
20.3 When to Consider Alternatives
20.4 Final Thoughts and Recommendations
Part I: Foundations
Chapter 1: Introduction to TanStack Query
1.1 History and Evolution
TanStack Query, formerly known as React Query, was created by Tanner Linsley in 2019 to address the challenges of data fetching and state management in React applications. The library was born out of frustration with existing solutions that either required too much boilerplate code or didn't handle the complex lifecycle of asynchronous data fetching effectively.
Initially released as React Query, the library quickly gained popularity due to its intuitive API and powerful features. The core innovation was its approach to treating server state differently from client state, recognizing that data from servers has unique characteristics:
- It is asynchronous by nature
- It can become stale or outdated
- It is shared across multiple components
- It requires caching and synchronization
In 2022, React Query evolved into TanStack Query to reflect its framework-agnostic nature. While it began as a React-specific library, the core logic was abstracted to support multiple frontend frameworks including Vue, Svelte, Solid, and Angular. This transformation represented a significant architectural shift, with the core query logic becoming framework-agnostic while maintaining framework-specific adapters.
The version history shows a thoughtful evolution:
- v1: Established the core API and concepts
- v2: Introduced improved TypeScript support and refined the API
- v3: Added significant performance improvements and new features like query filters
- v4: Rebranded as TanStack Query with a framework-agnostic core and improved bundle size
Throughout its evolution, TanStack Query has maintained backward compatibility while continuously refining its API based on real-world usage patterns and community feedback.
1.2 Core Philosophy and Design Principles
TanStack Query is built on several fundamental principles that guide its design and implementation:
1. Server State is Different from Client State
The most important philosophical distinction in TanStack Query is the recognition that server state and client state have fundamentally different characteristics and requirements. Server state:
- Is remotely persisted
- Requires asynchronous APIs for fetching
- Can be updated by other users
- Can become "stale" or out-of-date
- Has ownership that resides on the server
This distinction leads to a different approach compared to traditional state management libraries like Redux or MobX, which are primarily designed for client state.
2. Declarative Data Fetching
TanStack Query embraces declarative programming by allowing developers to describe what data they need rather than how to fetch it. This approach simplifies component code and makes data requirements explicit.
3. Stale-While-Revalidate as a Default Pattern
The library implements the stale-while-revalidate caching strategy by default, which means:
- Stale data is shown immediately while fresh data is being fetched
- Users see something immediately rather than loading spinners
- The UI updates automatically when fresh data arrives
4. Automatic Background Updates
TanStack Query handles many scenarios automatically that would otherwise require manual implementation:
- Refetching on window focus
- Refetching on network reconnection
- Polling at intervals
- Retry logic with exponential backoff
5. Separation of Concerns
The library separates:
- Data fetching logic from UI components
- Cache management from data fetching
- Synchronization logic from business logic
6. Developer Experience First
TanStack Query prioritizes developer experience with:
- Intuitive APIs that follow React patterns
- Comprehensive DevTools for debugging
- Detailed documentation and examples
- Strong TypeScript support
7. Progressive Complexity
The API is designed to be simple for basic use cases but allows for increasing complexity as needed:
- Basic queries require minimal configuration
- Advanced features are available but not required
- Escape hatches exist for custom behavior
These principles have guided the development of TanStack Query and explain many of the design decisions in the library.
1.3 Comparison with Other Data Fetching Solutions
To understand TanStack Query's position in the ecosystem, it's valuable to compare it with other approaches to data fetching and state management:
Raw Fetch/Axios with useState/useEffect
Traditional approach:
function Component() {
const [data, setData] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
setIsLoading(true);
try {
const response = await fetch('/api/data');
const result = await response.json();
setData(result);
} catch (err) {
setError(err);
} finally {
setIsLoading(false);
}
};
fetchData();
}, []);
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return <div>{data.name}</div>;
}
TanStack Query approach:
function Component() {
const { data, isLoading, error } = useQuery('data', fetchData);
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return <div>{data.name}</div>;
}
Advantages over raw fetching:
- Automatic caching
- Deduplication of requests
- Background refetching
- Loading and error states
- Retry logic
- Request cancellation
Redux with Thunks/Sagas
Redux requires significant boilerplate for async data fetching:
- Action creators for request, success, and failure
- Reducer logic to handle these actions
- Thunks or sagas for the actual API calls
- Selectors to access the data
TanStack Query eliminates this boilerplate while providing more features specifically designed for server state.
SWR (Stale-While-Revalidate)
SWR by Vercel is the closest alternative to TanStack Query, sharing many similar concepts:
- Both use the stale-while-revalidate pattern
- Both provide automatic revalidation
Key differences:
- TanStack Query has more advanced features like mutations, query invalidation, and infinite queries
- TanStack Query offers more configuration options
- TanStack Query has a more comprehensive DevTools experience
- TanStack Query is framework-agnostic (as of v4)
Apollo Client
Apollo Client is primarily designed for GraphQL, while TanStack Query is protocol-agnostic:
- Apollo has built-in GraphQL parsing and normalization
- TanStack Query works with any data fetching method (REST, GraphQL, WebSockets)
- Apollo has a larger bundle size due to its GraphQL-specific features
- TanStack Query has a simpler mental model for REST APIs
RTK Query
RTK Query is Redux Toolkit's data fetching solution:
- Integrated with Redux ecosystem
- Code generation for endpoints
- Similar caching mechanisms
TanStack Query differs in:
- Being independent of any state management library
- Having a more mature feature set
- Requiring less configuration
- Being more flexible with custom fetching logic
1.4 The TanStack Ecosystem
TanStack Query is part of a larger ecosystem of libraries created by Tanner Linsley and the TanStack community. Understanding this ecosystem helps contextualize TanStack Query's design and integration capabilities.
Core TanStack Libraries:
- TanStack Query: Data fetching and caching
- TanStack Router: Type-safe routing
- TanStack Table: Headless UI for building powerful tables and datagrids
- TanStack Virtual: Virtualization for large lists and grids
- TanStack Form: Form state management
- TanStack Store: Immutable state management
These libraries share common design principles:
- Framework agnostic with framework-specific adapters
- TypeScript-first development
- Headless UI approach (separation of logic and presentation)
- Composable APIs
- Performance-focused
TanStack Query Framework Adapters:
TanStack Query provides specific adapters for various frameworks:
- React Query (
@tanstack/react-query)
- Vue Query (
@tanstack/vue-query)
- Svelte Query (
@tanstack/svelte-query)
- Solid Query (
@tanstack/solid-query)
- Angular Query (
@tanstack/angular-query)
Each adapter implements the core TanStack Query logic with framework-specific bindings, allowing for a consistent API across different frontend frameworks.
Community Extensions:
The ecosystem also includes community-maintained extensions:
- Persistence adapters (localStorage, IndexedDB)
- Authentication helpers
- GraphQL integrations
- Testing utilities
Integration with Other Ecosystems:
TanStack Query is designed to work well with:
- Next.js and other SSR frameworks
- State management libraries like Redux or Zustand
- Form libraries like Formik or React Hook Form
- UI component libraries like Material-UI or Chakra UI
The modular nature of the TanStack ecosystem allows developers to adopt individual libraries as needed, rather than requiring an all-or-nothing approach.
Chapter 2: Core Concepts
2.1 Queries vs. Mutations
In TanStack Query, data operations are categorized into two fundamental types: queries and mutations. Understanding the distinction between these concepts is crucial for effectively modeling your application's data interactions.
Queries: Reading Data
Queries represent operations that retrieve data from a source without causing side effects. They are:
- Read-only: Queries don't modify server state
- Idempotent: Running the same query multiple times has the same effect as running it once
- Cacheable: Results can be stored and reused
- Potentially stale: The data they return may become outdated
Queries are defined by:
- A unique key that identifies the data
- A function that retrieves the data
- Configuration options that control caching behavior
Example of a basic query:
const { data, isLoading, error } = useQuery({
queryKey: ['todos'],
queryFn: fetchTodos,
staleTime: 5 * 60 * 1000, // 5 minutes
});
Mutations: Writing Data
Mutations represent operations that modify data, causing side effects on the server. They are:
- Write operations: They change server state
- Not automatically cached: Each mutation typically needs to be performed when requested
- Often invalidate queries: They frequently make existing cached data stale
Mutations are defined by:
- A function that performs the data modification
- Configuration options that control behavior and side effects
Example of a basic mutation:
const { mutate, isLoading, error } = useMutation({
mutationFn: addTodo,
onSuccess: () => {
// Invalidate and refetch
queryClient.invalidateQueries({ queryKey: ['todos'] });
},
});
// Later in your code
mutate({ title: 'Buy milk' });
Key Differences