Introduction to TanStack Query for Server State
Introduction to TanStack Query for Server State
1. The Server State vs Client State Paradigm
In React development, engineers historically treated all data the same—dumping both UI state and fetched API data into useState, useReducer, or Redux.
However, modern engineering distinguishes between two fundamentally different types of state:
- 1Client State (UI State): Data wholly owned by the browser that is synchronous and always up-to-date (e.g. modal open/closed, active tab, form inputs).
- 2Server State (Remote Cache): Data owned by a remote server that is asynchronous, shared across multiple users, requires serialization, and can become stale at any moment without your knowledge (e.g. user profile, course list, stock prices).
Using raw useEffect and useState for server state forces you to manually write hundreds of lines for caching, deduplication, retry logic, background refetching, and pagination.
TanStack Query (formerly React Query) is the industry standard for managing server state in modern web applications.
2. Installing TanStack Query
3. Setting Up QueryClientProvider
Wrap your application root with QueryClientProvider:
4. Fetching Data with useQuery
To fetch and cache data, call the useQuery hook:
5. Superpowers Out of the Box
By adopting TanStack Query:
- Automatic Caching: If two components request
['courses'], only one network request is sent! - Window Focus Refetching: When a user tabs back to your application after reading an email, TanStack Query automatically refreshes stale data in the background.
- Deduplication: Multiple rapid calls are merged into a single network flight.
Practice Quiz
useQuery?useQuery({ queryKey: ['userData'], ... })?staleTime configure in TanStack Query?Managing Pagination, Caching, and Background Refetch
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Handling HTTP POST, PUT, and DELETE Mutations | Managing Pagination, Caching, and Background Refetch |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.