Abbottabad, KPK
BlogMarch 22, 2026

Modern React State Architecture: TanStack Query and Redux Toolkit

Haseeb Gul
Managing state effectively is one of the biggest challenges in complex React applications. In developer communities, you will frequently see debates framed as "TanStack Query vs. Redux Toolkit", suggesting that developers must choose one over the other. This framing is a false dichotomy. TanStack Query and Redux Toolkit are not competitors; they are built for two completely different purposes:
  • 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.
When these two concerns are conflated—such as manually stuffing remote API payloads into Redux slices—the result is boilerplate overload, duplicated API logic, unnecessary re-renders, and brittle cache invalidation. A scalable, maintainable architecture treats server state, client state, and real-time communication as distinct layers with dedicated owners:
  • 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 goal is never to force one state-management library to do everything. The goal is to give each category of state the exact tool built for it. A typical React application using this approach can be organized around three primary state boundaries:
Text
+-----------------------------------------------------------------------+
|                       REACT APPLICATION                               |
|                                                                       |
|  +----------------------+       +-------------------------------+     |
|  |    UI Components     |       |     Feature Components        |     |
|  |                      |       |                               |     |
|  | Buttons, Forms,      |       | Sessions, Users, Dashboard,   |     |
|  | Modals, Drawers      |       | Notifications, Calls          |     |
|  +----------+-----------+       +---------------+---------------+     |
|             |                                   |                     |
|             +----------------+------------------+                     |
|                              |                                        |
|              +---------------+---------------+                        |
|              |                               |                        |
|              v                               v                        |
|    +-------------------+          +-------------------------+         |
|    | Redux Toolkit     |          | TanStack Query          |         |
|    | Client State      |          | Server State            |         |
|    |                   |          |                         |         |
|    | Theme             |          | API Responses           |         |
|    | Sidebar           |          | Users / Sessions        |         |
|    | Filters           |          | Notifications           |         |
|    | UI Preferences    |          | Cached Remote Data      |         |
|    +-------------------+          +------------+------------+         |
|                                               |                       |
+-----------------------------------------------|-----------------------+
                                                |
                                  +-------------+-------------+
                                  |                           |
                                  v                           v
                         +------------------+       +-------------------+
                         | Axios / HTTP     |       | WebSocket Client  |
                         |                  |       |                   |
                         | REST APIs        |       | Real-time Events  |
                         | Auth Headers     |       | Signaling         |
                         | Interceptors     |       | Presence          |
                         +--------+---------+       +---------+---------+
                                  |                           |
                                  v                           v
                         +------------------+       +-------------------+
                         | Backend API      |       | Signaling Server  |
                         +------------------+       +---------+---------+
                                                            |
                                                            v
                                                   +------------------+
                                                   | WebRTC Peers     |
                                                   |                  |
                                                   | Direct Media     |
                                                   | Data Channels    |
                                                   +------------------+
This separation makes the data flow easier to reason about. Components consume state rather than implementing the infrastructure required to maintain that state. The first architectural decision is determining whether a piece of data belongs to the server or to the client. Server state is data that originates outside the browser on a remote database or service. The frontend does not own this data—it merely holds a temporary, cached snapshot of it. Because other users or background jobs can modify it at any time, server data is inherently asynchronous, can become stale without the frontend's knowledge, and requires caching, deduplication, and periodic synchronization. Examples include authenticated user sessions, products, active WebRTC rooms, notifications, permissions, and dashboard analytics. Client state belongs entirely to the frontend application inside the browser tab. It is synchronous, immediate, deterministic, and 100% application-owned. It has no external backend database to synchronize against. Examples include whether a sidebar drawer is open, which modal is visible, the current theme (light/dark), temporary table filters, or an in-progress multi-step form draft.
Category
Best Tool
Examples
Key Characteristics
Server StateTanStack QueryUsers, sessions, messages, API responsesRemote, asynchronous, cached, potentially stale, shared across components
HTTP TransportAxiosGET, POST, PUT, PATCH, DELETE requestsHandles requests, headers, interceptors, serialization, and errors
Client StateRedux ToolkitTheme, sidebar, filters, UI preferencesSynchronous application-owned state
Local Component StateReact useStateInput values, hover state, temporary UIShort-lived state that does not need to be globally shared
Real-time EventsWebSocketsPresence, signaling, live notificationsEvent-driven updates pushed from a server
Peer-to-Peer DataWebRTCAudio, video, data channelsDirect browser-to-browser communication when possible
The critical insight is that TanStack Query and Redux Toolkit serve two completely different purposes. A common architectural trap is stuffing API responses into Redux simply because Redux is already installed. This forces developers to manually write loading booleans, error objects, cache timestamps, retry counters, and synchronization reducers. If data originates from a server and requires caching or background synchronization, TanStack Query is purpose-built for the job. TanStack Query is not an ordinary state container; it is an asynchronous server-state synchronization engine. In traditional React, managing remote data requires manually handling loading, error, and data states:
Tsx
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
This pattern forces every component to duplicate fetch logic, manage race conditions, handle unmounting, and trigger unwanted loading spinners on every page change. TanStack Query manages the entire server-state lifecycle under the hood:
  1. 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.
  2. 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.
  3. 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.
Here is a practical custom hook managing active WebRTC sessions:
hooks/useActiveSessions.ts
import { useQuery } from "@tanstack/react-query";
import axios from "axios";

// Fetch active WebRTC sessions from the backend.
export function useActiveSessions() {
return useQuery({
  queryKey: ["active-sessions"],

  queryFn: async () => {
    const { data } = await axios.get("/api/sessions");
    return data;
  },

  // Server-state cache configuration:
  staleTime: 1000 * 30, // Data stays "fresh" for 30s before refetching
  gcTime: 1000 * 60 * 5, // Keep unused cache in memory for 5 minutes
});
}
The consuming component receives { data, isLoading, error, refetch } directly. It never needs to worry about HTTP serialization, caching policies, or whether another component has already triggered the same request. Two critical settings govern TanStack Query's server-state cache:
  • 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.
TanStack Query uses query keys to identify cached server data. For example:
Tsx
["active-sessions"]
identifies one logical resource. A user-specific query could instead use:
Tsx
["user", userId]
while a paginated list might use:
Tsx
["sessions", { page, status }]
This allows different components to access the same server state without maintaining independent copies. For example:
Tsx
const { data } = useQuery({
  queryKey: ["sessions", { status: "active" }],
  queryFn: () => fetchSessions({ status: "active" }),
});
If multiple components request the same query key, TanStack Query can coordinate the cached result instead of forcing every component to implement its own request lifecycle. Fetching data is only half of server-state management. Applications also need to create, update, and delete remote resources. TanStack Query provides mutations for these operations.
hooks/useEndSession.ts
import { useMutation, useQueryClient } from "@tanstack/react-query";
import axios from "axios";

export function useEndSession() {
const queryClient = useQueryClient();

return useMutation({
  mutationFn: async (sessionId: string) => {
    const { data } = await axios.delete(
      "/api/sessions/" + sessionId
    );

    return data;
  },

  onSuccess: () => {
    queryClient.invalidateQueries({
      queryKey: ["active-sessions"],
    });
  },
});
}
After the mutation succeeds, the active-session query can be invalidated. The next render can therefore receive refreshed server data without manually updating several Redux objects or component states. This is one of the major benefits of treating remote data as server state instead of ordinary application state. Axios and TanStack Query have different responsibilities. Axios is responsible for making HTTP requests. TanStack Query is responsible for managing the lifecycle of the resulting server state. A useful mental model is:
Text
React Component
       |
       v
TanStack Query
       |
       v
     Axios
       |
       v
   HTTP API
       |
       v
    Backend
Axios can handle concerns such as:
  • Base URLs
  • Authorization headers
  • Request interceptors
  • Response interceptors
  • Request serialization
  • HTTP errors
  • Timeouts
  • Request configuration
TanStack Query handles concerns such as:
  • Caching
  • Query lifecycle
  • Loading states
  • Error states
  • Refetching
  • Stale data
  • Query invalidation
  • Mutation lifecycle
  • Synchronizing server data between components
Keeping these responsibilities separate makes the architecture easier to replace and test. Just as TanStack Query excels at managing remote asynchronous data, Redux Toolkit (RTK) excels at managing synchronous, shared client-side state. Not every piece of application data comes from an API. Consider a complex frontend dashboard or real-time communication platform with:
  • 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
None of these values belong to the backend database. They are 100% application-owned, live inside the browser tab, and must update synchronously and deterministically. Redux Toolkit eliminates the legacy boilerplate of historical Redux by utilizing modern patterns:
  1. Deterministic Unidirectional Flow: User interactions trigger dispatch(action). Pure reducer functions compute the new state tree.
  2. 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.
  3. 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.
  4. 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.
Here is a clean client-side UI slice:
store/uiSlice.ts
import { createSlice, PayloadAction } from "@reduxjs/toolkit";

interface UIState {
isSidebarOpen: boolean;
activeFilter: string;
activeTheme: "light" | "dark";
}

const initialState: UIState = {
isSidebarOpen: true,
activeFilter: "all",
activeTheme: "dark",
};

export const uiSlice = createSlice({
name: "ui",
initialState,

reducers: {
  toggleSidebar: (state) => {
    // Immer allows direct mutation syntax safely
    state.isSidebarOpen = !state.isSidebarOpen;
  },

  setFilter: (state, action: PayloadAction<string>) => {
    state.activeFilter = action.payload;
  },

  setTheme: (
    state,
    action: PayloadAction<"light" | "dark">
  ) => {
    state.activeTheme = action.payload;
  },
},
});

export const {
toggleSidebar,
setFilter,
setTheme,
} = uiSlice.actions;

export default uiSlice.reducer;
The true power of this architecture becomes obvious when a single feature component uses both libraries side by side. Instead of fighting, each library handles what it was designed for:
  • 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
import { useQuery } from "@tanstack/react-query";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";
import { setFilter } from "../store/uiSlice";
import type { RootState } from "../store";

export function SessionsDashboard() {
const dispatch = useDispatch();

// 1. CLIENT STATE (Redux Toolkit): Synchronous user-selected UI filter
const activeFilter = useSelector((state: RootState) => state.ui.activeFilter);

// 2. SERVER STATE (TanStack Query): Asynchronous remote data cached by filter key
const { data: sessions, isLoading } = useQuery({
  queryKey: ["sessions", activeFilter],
  queryFn: async () => {
    const { data } = await axios.get(`/api/sessions?status=${activeFilter}`);
    return data;
  },
  staleTime: 1000 * 30,
});

return (
  <div className="dashboard-container">
    {/* UI action dispatches to Redux */}
    <div className="filter-controls">
      <button onClick={() => dispatch(setFilter("all"))}>All</button>
      <button onClick={() => dispatch(setFilter("active"))}>Active</button>
      <button onClick={() => dispatch(setFilter("ended"))}>Ended</button>
    </div>

    {/* Render remote server state */}
    {isLoading ? (
      <p>Loading sessions...</p>
    ) : (
      <ul>
        {sessions?.map((session: any) => (
          <li key={session.id}>{session.title}</li>
        ))}
      </ul>
    )}
  </div>
);
}
Notice how clean the division is:
  1. When the user clicks "Active", Redux synchronously dispatches setFilter("active").
  2. The component reads the new activeFilter from Redux.
  3. TanStack Query detects the queryKey change from ["sessions", "all"] to ["sessions", "active"].
  4. If ["sessions", "active"] is already in TanStack Query's cache, it is rendered instantly without waiting on the network.
  5. If it is not in the cache, TanStack Query fetches it via Axios and caches the result for future renders.
Neither library overlaps. Neither library creates duplicate state. They collaborate seamlessly. A useful rule is:
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
Redux
 └── user
      ├── id
      ├── name
      ├── avatar
      └── permissions
But now the application needs to decide:
  • 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?
These are server-state problems. A query is often a more natural representation:
Tsx
const userQuery = useQuery({
  queryKey: ["user", userId],
  queryFn: () => getUser(userId),
});
Redux can then remain focused on state that belongs to the client. Not every UI value needs Redux. For example, a search input that exists only inside one component can remain local:
Tsx
const [search, setSearch] = useState("");
A useful hierarchy is:
Text
Component-local state
        |
        |-- useState / useReducer
        |
        v
Shared client state
        |
        |-- Redux Toolkit
        |
        v
Remote server state
        |
        |-- TanStack Query
        |
        v
Real-time communication
        |
        |-- WebSockets
        |
        v
Peer-to-peer communication
        |
        |-- WebRTC
The goal is not to move everything into global state. The goal is to keep state as close as possible to the system that owns it. Real-time applications introduce another layer. For example, a video-conferencing application might have this flow:
Text
+-----------------------------------------------------------------------+
|                    WEBRTC PEER CONNECTION FLOW                        |
|                                                                       |
|   [Peer A]                                                            |
|      |                                                                |
|      | 1. WebSocket: SDP Offer                                        |
|      v                                                                |
|   [Signaling Server]                                                  |
|      |                                                                |
|      | 2. Forward SDP Offer                                           |
|      v                                                                |
|   [Peer B]                                                            |
|      |                                                                |
|      | 3. SDP Answer                                                  |
|      +---------------------------> [Signaling Server]                 |
|                                      |                                |
|                                      | 4. Forward Answer              |
|                                      v                                |
|                                  [Peer A]                             |
|                                                                       |
|   After ICE Negotiation:                                              |
|                                                                       |
|   [Peer A] ================= Direct WebRTC ================= [Peer B] |
|                    Audio / Video / Data                               |
|                                                                       |
|   If Direct P2P Connection Fails:                                     |
|                                                                       |
|   [Peer A] -------- WebRTC --------> [TURN Relay] --------> [Peer B] |
|                                                                       |
+-----------------------------------------------------------------------+
The important point is that WebSockets and WebRTC are not replacements for TanStack Query or Redux Toolkit. They operate at different layers. WebSockets can deliver real-time events such as:
Text
user.online
user.offline
session.created
session.ended
notification.created
webrtc.offer
webrtc.answer
ice.candidate
WebRTC can then establish the actual peer-to-peer media or data connection. For example:
Text
                    Signaling Layer
                         |
                    WebSocket
                         |
        +----------------+----------------+
        |                                 |
      Peer A                            Peer B
        |                                 |
        +---------- WebRTC ---------------+
                    |
          Audio / Video / Data
A WebSocket event does not necessarily need to become Redux state. For example, when the server sends:
Text
session.created
the application can use that event to invalidate or update a TanStack Query cache. Conceptually:
Tsx
socket.on("session.created", () => {
  queryClient.invalidateQueries({
    queryKey: ["active-sessions"],
  });
});
The WebSocket is responsible for transporting the event. TanStack Query remains responsible for server-state synchronization. This separation is especially useful in dashboards where data needs to remain synchronized without polling aggressively. When deciding where a piece of state should live, ask these questions:
Text
                    Is the data remote?
                         |
                +--------+--------+
                |                 |
               YES               NO
                |                 |
                v                 v
        Does it need cache?   Is it shared?
                |                 |
          +-----+-----+       +---+---+
          |           |       |       |
         YES          NO     YES      NO
          |           |       |       |
          v           v       v       v
   TanStack Query   API/     Redux   useState
                   local
                  handling
For real-time data, add another question:
Text
Does the server push updates?

        |
       YES
        |
        v
    WebSocket
        |
        v
Update / invalidate
server-state cache
        |
        v
TanStack Query
This prevents a common mistake: treating the communication mechanism as the state-management mechanism. A feature-oriented project structure can make these boundaries explicit:
Text
src/
├── app/
│   ├── store.ts
│   ├── queryClient.ts
│   └── providers.tsx
│
├── features/
│   ├── sessions/
│   │   ├── api/
│   │   │   ├── getSessions.ts
│   │   │   └── endSession.ts
│   │   ├── hooks/
│   │   │   ├── useActiveSessions.ts
│   │   │   └── useEndSession.ts
│   │   ├── components/
│   │   │   └── SessionList.tsx
│   │   └── types.ts
│   │
│   ├── ui/
│   │   └── uiSlice.ts
│   │
│   └── realtime/
│       ├── socket.ts
│       ├── events.ts
│       └── webrtc.ts
│
├── components/
│   ├── Button.tsx
│   ├── Modal.tsx
│   └── Sidebar.tsx
│
└── lib/
    └── axios.ts
This structure makes it easier to understand where new code belongs. API communication stays near the feature that owns it, shared UI state remains in Redux, and real-time infrastructure has its own boundary. One of the most important architectural principles is to avoid storing the same data in multiple places. For example, avoid this:
Text
Backend
   |
   +----> TanStack Query
   |
   +----> Redux
   |
   +----> Component State
Now the same user/session/message may exist in three different representations. Instead, prefer:
Text
                    Backend
                       |
              +--------+--------+
              |                 |
           HTTP/API          WebSocket
              |                 |
              v                 v
       TanStack Query      Event Handler
              |                 |
              +--------+--------+
                       |
                       v
                 React UI
                       
        Redux Toolkit
              |
              v
       Client-only state
There should ideally be one authoritative source for each category of state. State architecture also affects rendering performance. If a rapidly changing server response is stored in a large global Redux object, many unrelated subscribers may potentially become involved in updates. Likewise, putting every small UI interaction into a global store adds unnecessary complexity. A better strategy is to scope state according to its ownership:
Text
Frequently changing local value
        -> useState

Shared UI configuration
        -> Redux Toolkit

Cached API response
        -> TanStack Query

Server-pushed event
        -> WebSocket

Audio/video/data stream
        -> WebRTC
This does not automatically make an application fast, but it creates cleaner boundaries for optimizing it. Redux should not automatically become the application's API cache. If remote data requires caching, refetching, stale-time management, and invalidation, use a server-state solution. A sidebar's open/closed state does not need server caching. Using TanStack Query for this kind of state adds complexity without providing a meaningful benefit. A WebSocket is a communication channel. It tells the client that something happened, but it does not necessarily provide the complete authoritative state of the application. The backend remains the source of truth. WebSockets may be used to exchange SDP offers, SDP answers, and ICE candidates. They are part of the signaling process. After negotiation, WebRTC can establish the actual peer-to-peer connection. If a session exists simultaneously in Redux, component state, and TanStack Query, synchronization becomes difficult. Prefer one owner and derive other UI representations from it. A modern React application can therefore use a layered architecture:
Text
+-------------------------------------------------------------------+
|                         React UI                                 |
|                                                                   |
|   Components / Pages / Features                                  |
+---------------------------+---------------------------------------+
                            |
            +---------------+---------------+
            |                               |
            v                               v
+---------------------------+     +-------------------------------+
| Client State              |     | Server State                  |
|                           |     |                               |
| Redux Toolkit             |     | TanStack Query                |
|                           |     |                               |
| Theme                     |     | API responses                 |
| Sidebar                   |     | Users                         |
| Filters                   |     | Sessions                      |
| UI preferences            |     | Notifications                 |
+---------------------------+     +---------------+---------------+
                                                |
                                                v
                                     +---------------------+
                                     | Axios / HTTP API    |
                                     +----------+----------+
                                                |
                                                v
                                          Backend Server
                                                |
                                                |
                                     +----------+----------+
                                     |                     |
                                     v                     v
                               WebSocket              REST API
                                     |                     |
                                     v                     |
                              Real-time Events             |
                                     |                     |
                                     +----------+----------+
                                                |
                                                v
                                           WebRTC Layer
                                                |
                                    +-----------+-----------+
                                    |                       |
                                    v                       v
                                  Peer A                  Peer B
This architecture creates a clear separation of responsibilities: | Layer | Responsibility | | -------------- | --------------------------------------- | | React | Rendering and composition | | useState | Component-local state | | Redux Toolkit | Shared client-side state | | TanStack Query | Cached server state | | Axios | HTTP transport | | WebSockets | Real-time event transport and signaling | | WebRTC | Peer-to-peer media and data |
The best state-management architecture is rarely about choosing a single library. Instead, assign each responsibility to the tool designed for it:
Text
                 WHAT KIND OF STATE IS IT?
                           |
          +----------------+----------------+
          |                |                |
          v                v                v
       Local UI        Client State      Server State
          |                |                |
      useState         Redux Toolkit   TanStack Query
                                             |
                                             v
                                      Axios / API
                                             |
                                             v
                                      Backend Server
                                             |
                                             v
                                      WebSocket Events
                                             |
                                             v
                                          WebRTC
TanStack Query manages asynchronous server-side state (remote data, caching, deduplication, and synchronization). Redux Toolkit manages synchronous client-side state (UI preferences, active modals, and client workflows). Axios handles HTTP transport. WebSockets provide real-time events and signaling, while WebRTC handles peer-to-peer communication. Keeping these responsibilities separate makes React applications easier to scale, debug, test, and maintain as the number of features and real-time interactions grows.