- TanStack Query is an asynchronous server-side state management and caching engine. It is responsible for fetching, caching, synchronizing, deduplicating, and revalidating remote data that originates from your backend.
- Redux Toolkit is a synchronous client-side state management library. It is responsible for managing application-owned global UI state, theme toggles, modal dialogs, navigation filters, and complex client-side workflows.
- TanStack Query: Manages asynchronous server-side state and caching.
- Axios: Provides the underlying HTTP transport layer.
- Redux Toolkit: Manages synchronous, shared client-side application state.
- WebSockets: Handles real-time signaling, presence, and event delivery.
- WebRTC: Handles direct peer-to-peer audio, video, or data communication.
The Core Architecture
Text
Server State vs. Client State: Two Different Purposes
Server-Side State
Client-Side State
How TanStack Query Works: Server-Side State Management
Tsx
- Stale-While-Revalidate Engine: When a component requests data, TanStack Query immediately serves the cached snapshot from memory (if available) so the user experiences zero UI delay. In the background, it silently verifies freshness with the server and updates the UI only if the data has changed.
- Automatic Request Deduplication: If three different components on the screen mount at the same time and request the same query key, TanStack Query merges them into a single HTTP request, eliminating redundant network traffic.
- Window Focus & Network Re-validation: When a user leaves your tab to check an email and comes back, TanStack Query automatically refetches stale queries in the background, keeping the UI fresh without manual page reloads.
hooks/useActiveSessions.ts
The Mechanics of Stale Time vs. Garbage Collection Time
- staleTime: The duration until cached data is considered stale. While fresh, queries read directly from cache without hitting the network. Once stale, queries continue serving cached data immediately to the UI while triggering a background refetch.
- gcTime (formerly cacheTime): The duration inactive or unmounted queries stay in memory. If no components are actively observing a query, it remains in memory for this duration before TanStack Query clears it from memory.
Why Query Keys Matter
Tsx
Tsx
Tsx
Tsx
Mutations and Cache Invalidation
hooks/useEndSession.ts
Axios: Transport Layer, Not State Management
Text
- Base URLs
- Authorization headers
- Request interceptors
- Response interceptors
- Request serialization
- HTTP errors
- Timeouts
- Request configuration
- Caching
- Query lifecycle
- Loading states
- Error states
- Refetching
- Stale data
- Query invalidation
- Mutation lifecycle
- Synchronizing server data between components
How Redux Toolkit Works: Client-Side State Management
- A collapsible sidebar toggle
- A selected navigation tab or active route view
- A theme preference ("light" vs "dark")
- Multi-step wizard drafts and client-side form controls
- Global modal and drawer managers
- Client-side audio/video mute states during a WebRTC call
The Mechanics of Redux Toolkit
- Deterministic Unidirectional Flow: User interactions trigger dispatch(action). Pure reducer functions compute the new state tree.
- Simplified Immutability with Immer: Under the hood, createSlice wraps reducers in Immer. Developers write standard mutable-looking JavaScript (state.isSidebarOpen = !state.isSidebarOpen), while Immer safely produces a new frozen immutable state tree.
- Synchronous Execution: Client-state actions resolve immediately in memory. There are no network latency delays, loading spinners, or retry mechanisms needed for flipping a sidebar or setting a theme.
- Selective Subscriptions: Components subscribe using useSelector((state) => state.ui.theme). Only components subscribed to that specific slice re-render when that property changes, protecting rendering performance across large component trees.
store/uiSlice.ts
In Harmony: How TanStack Query and Redux Work Together
- Redux Toolkit controls the client-side UI filter chosen by the user.
- TanStack Query receives that filter in its queryKey and manages the server data fetching, caching, and deduplication.
features/sessions/components/SessionsDashboard.tsx
- When the user clicks "Active", Redux synchronously dispatches setFilter("active").
- The component reads the new activeFilter from Redux.
- TanStack Query detects the queryKey change from ["sessions", "all"] to ["sessions", "active"].
- If ["sessions", "active"] is already in TanStack Query's cache, it is rendered instantly without waiting on the network.
- If it is not in the cache, TanStack Query fetches it via Axios and caches the result for future renders.
What Should NOT Go Into Redux?
If deleting the backend would make the state disappear, it is probably server state.For example, consider an authenticated user profile. Putting it into Redux may initially look convenient:
Text
- When should the user be refetched?
- What happens after a profile update?
- How long is the cached profile valid?
- What happens when another component updates the same user?
- How should stale data be detected?
- How should failed requests be retried?
Tsx
Local State Still Has a Place
Tsx
Text
Real-Time State: WebSockets and WebRTC
Text
Text
Text
Combining WebSockets with TanStack Query
Text
Tsx
A Practical Decision Tree
Text
Text
Recommended Project Structure
Text
Avoiding Duplicate Sources of Truth
Text
Text
Performance and Re-Rendering
Text
Common Architectural Mistakes
1. Putting Every API Response Into Redux
2. Using TanStack Query for Pure UI State
3. Treating WebSockets as a Database
4. Mixing WebRTC Signaling With Media Transport
5. Creating Multiple Sources of Truth
Putting Everything Together
Text
Common Questions
Are TanStack Query and Redux Toolkit competitors?
Should I use Redux Toolkit and TanStack Query together?
Should API responses ever be stored in Redux?
How does Axios fit into this architecture?
Where should WebSocket events be stored?
Is WebSocket the same as WebRTC?
When should I use useState instead of Redux?
Can WebSockets update TanStack Query?
Final Takeaway
Text