State Management in React: Separating Server State from Client State

Separate server, URL, form and client state in React state management; choosing between TanStack Query, Context, Zustand and Redux Toolkit, and the order for getting out of a bloated store.
Technical summary
Technology
React, TanStack Query, SWR, Zustand, Redux Toolkit, React Router
Topic
Separating state types in a React application and choosing tools
Level
Intermediate–advanced
Prerequisites
  • Knowledge of React hooks (useState, useEffect)
  • Experience working with a REST or GraphQL API
In this article7 sections

When you open up a bloated Redux store, what you see is often not client state: order lists, user records, isLoading flags, lastFetched timestamps kept by hand. All of these are copies of data living on the server, and the store turns into a pile of code to refresh them and keep them consistent. That’s why the question “which state library should we choose?” is asked from the wrong starting point. First split the state into types; the choice of tool comes after.

Separating state types

Before getting into the library debate, place every piece of state in the app into one of the four classes below. This distinction is more decisive than which tool you choose.

Type Real owner Example Suitable tool
Server state Backend / API Order list, user profile TanStack Query, SWR
URL state Address bar Filter, page number, sort, selected tab Router search parameters
Form state Form component Fields being edited, validation errors React Hook Form, local state
Client (UI) state Browser session Open modal, theme, cart draft useState, Context, Zustand, Redux Toolkit

Server state is fundamentally different from the other three: someone else can change it, it can go stale while you’re looking at the screen, and it arrives asynchronously. You manage it not like a variable but like a cache of a remote source. A single question is enough to find a value’s class: “When I refresh the page, where should this value come back from?” If the answer is the API, it’s server state; if it’s the address bar, URL state; if it shouldn’t come back from anywhere, client state. Ask this question of every slice in the store. The table fills itself in.

Server state and data caching libraries

TanStack Query and SWR cache server data under a key (the query key). They manage loading and error states, background revalidation, merging simultaneous requests (deduplication) and invalidation after changes for you. A large part of the code that keeps isLoading, error and lastFetched fields by hand in Redux disappears with these libraries.

// Order list and update with TanStack Query v5
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';

export function useOrders(filters: { status: string; page: number }) {
  return useQuery({
    queryKey: ['orders', filters],          // the filter is part of the key
    queryFn: () => api.get('/orders', { params: filters }),
    staleTime: 30_000,                       // treat as fresh for 30 s
  });
}

export function useApproveOrder() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => api.post(`/orders/${id}/approve`),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['orders'] }),
  });
}

Three settings decide things in this code. Query key design: if filters aren’t in the key, the results of different filters overwrite each other; the user switches to the “Approved” tab but sees “Open” orders for a moment. staleTime: the default is zero, the data is considered “stale” immediately and is fetched again in the background when the component remounts, the window regains focus or the network connection is re-established. For rarely changing reference data such as country lists and product categories, raising this value cuts unnecessary requests. Invalidation scope: invalidating with the ['orders'] prefix refreshes all filter combinations; giving a narrower key is possible but increases the risk of inconsistency.

In Next.js App Router projects, some of the data is fetched in a Server Component and never reaches the client as state. In that case, a client-side query library is only needed in interactive sections: infinite scroll, live filters, refreshing after a mutation. Where to draw the line is explained in detail in the Server and Client Components in the Next.js App Router guide.

When should optimistic updates be used?

For operations where immediate feedback is expected, such as an approve button, starring or changing the sort order, an optimistic update changes the interface without waiting for the server response and rolls back if an error returns. For operations where an amount, stock or permission changes, wait for the server response. Showing the user “approved” and rolling it back two seconds later shakes trust in business processes. There’s no optimism with money.

URL and form state

When the filter, page number and sort order on the list screens of corporate business applications are put in a global store, three complaints come in: a shared link doesn’t open the same view, the browser’s back button doesn’t work as expected, and the user starts over when the page is refreshed. This is usually the source of the “I sent the link but the other person sees a different list” ticket that lands on the support team. The natural place for this information is the URL.

// React Router v6: keeping the filter in the URL
// (in v7 the same hook can also be imported from the 'react-router' package)
import { useSearchParams } from 'react-router-dom';

function OrderFilters() {
  const [params, setParams] = useSearchParams();
  const status = params.get('status') ?? 'open';
  const page = Number(params.get('page') ?? '1');

  const { data } = useOrders({ status, page }); // the list is rendered in a separate component

  return (
    <select
      value={status}
      onChange={(e) => setParams({ status: e.target.value, page: '1' })}
    >
      <option value="open">Open</option>
      <option value="approved">Approved</option>
    </select>
  );
}

URL parameters are text. When converting them to a number, date or list, fall back to the default on an invalid value; a hand-typed ?page=abc shouldn’t crash the screen. In Next.js, the same pattern is set up with useSearchParams and useRouter, and in the App Router also on the server side with the page component’s searchParams prop (in Next.js 15 and later, this prop arrives as a Promise and must be awaited).

Form state is short-lived: it exists while the form is open and loses its meaning after submission. Writing every keystroke to a global store produces unnecessary re-renders and creates conflicts on screens where several forms are open. Libraries such as React Hook Form keep field values inside the component; submission to the server is a mutation and belongs to the server state layer. Sharing validation rules between client and server is the subject of the managing form validation with a single schema guide.

Options for global client state

Once the three types are separated, the real client state that remains is usually small: the user’s interface preferences, theme, an open sidebar, a multi-step wizard’s draft, a local cart. The options are:

  • useState / useReducer and lifting state up: If a few components use the state, this is the first choice. If there are complex transitions, useReducer makes the logic testable.
  • Context: A mechanism for distributing a value through the tree without passing props; it isn’t a state management library. When the Context value changes, all components reading it re-render. It suits rarely changing values such as theme, language and session information; with frequently changing values it causes performance problems.
  • Zustand: A store with a small API that doesn’t need a provider. Components subscribe only to the part they need with a selector, and unrelated changes don’t trigger a render.
  • Redux Toolkit: Offers a strict one-way data flow, time travel with Redux DevTools, a middleware ecosystem and integrated server state management with RTK Query. It gives predictability and auditability in a large team; in return it asks for more structure.
// Zustand: subscribing with a selector
import { create } from 'zustand';

type UiState = { sidebarOpen: boolean; toggleSidebar: () => void };

export const useUi = create<UiState>()((set) => ({
  sidebarOpen: true,
  toggleSidebar: () => set((s) => ({ sidebarOpen: !s.sidebarOpen })),
}));

// The component renders only when sidebarOpen changes
const open = useUi((s) => s.sidebarOpen);

Library comparison table

Criterion Context Zustand Redux Toolkit
Extra dependency None Small Medium (RTK + react-redux)
Partial subscription with selectors No (by splitting the Context) Yes Yes (useSelector)
DevTools / tracing React DevTools Redux DevTools via middleware Built in
Server state support None None (together with Query) RTK Query
Suitable scale A few rarely changing values Small to medium client state Large team, complex business rules

In practice, the decision order works like this: first determine the class of the state; give server state to the query library and URL state to the router. If the remaining client state is within a single screen, local state is enough. If it’s app-wide and changes rarely, Context fits; if it changes often and many components read it, Zustand. If the team has already invested in Redux Toolkit and wants to keep server state under the same roof with RTK Query, simplifying the existing structure is cheaper than switching libraries. A rewrite is usually the most expensive path.

For the effect of the API-side choice on the client cache, see the REST or GraphQL comparison; since GraphQL clients (e.g. Apollo Client) bring their own normalized cache, a separate query library may not be needed.

Steps for getting rid of excessive global state

Rewriting the Redux store of a corporate web application that has grown over the years in one go is like replacing the core switch of a live system during business hours. The sequence below proceeds without breaking features and keeps the rollback path open.

  1. Take an inventory. List every slice in the store and assign it to one of the four classes. In most projects it turns out that lists, detail records and loading flags are server state.
  2. Set up the query library alongside. Add TanStack Query’s QueryClientProvider together with the Redux Provider. The two systems can run side by side for a while.
  3. Move read endpoints one at a time. Start with the simplest list screen: replace the thunk + reducer + selector trio with a useQuery hook. Before deleting the slice, verify with a code search that nothing else reads it.
  4. Move mutations. Move save and approve operations to useMutation; instead of updating the store by hand after success, invalidate the relevant queries.
  5. Move filters into the URL. Move the filter and pagination information in the store to search parameters; deep linking and back button behavior fix themselves.
  6. Shrink the remaining client state. If a few UI slices remain, leaving them in Redux or moving them to Zustand is the team’s preference. The goal isn’t a library but a simple state model.

Common mistakes

  • Copying server data: This is the mistake we see most often in the field. Writing a useQuery result into separate state inside useEffect creates two sources of truth, and one of them inevitably falls behind. Calculate derived values during render or use the select option.
  • Storing derivable values: If a total amount, a filtered list or the number of selected items can be calculated from other state, it isn’t stored separately.
  • One giant Context: Putting the user, theme, notifications and cart in the same Context value causes the whole app to re-render when one of them changes. Split Contexts by responsibility.
  • A missing parameter in the query key: Every variable the request function uses must be in the key; TanStack Query’s ESLint plugin (@tanstack/eslint-plugin-query) includes a rule that catches this mistake.

Don’t proceed without measuring while the migration is under way. Compare render counts and durations on critical screens before and after with the React DevTools Profiler; look for duplicate requests to the same endpoint in the browser’s network tab. If the same endpoint is called three times when a page opens, the cache key is wrong. To keep type definitions and folder boundaries in the state layer consistent across the team, apply the module boundary approach in the TypeScript codebase standards guide together with this work.

To simplify the state layer of an existing React app or build this separation into a new project from the start, we carry out architecture assessments within the scope of our React and Next.js web applications service. For conceptual background, the Managing State section of the React documentation and the TanStack Query documentation are the primary sources.

Frequently asked questions

Is Redux unnecessary now?

No. Once server state moves to a query library, the work left in Redux shrinks. In projects with complex client-side business rules, a need for time-travel debugging and a large team wanting a strict structure, Redux Toolkit is still a sensible choice.

How do you choose between TanStack Query and SWR?

Both cache server state and revalidate in the background. SWR offers a smaller API; TanStack Query is more comprehensive on mutations, invalidation, infinite queries and DevTools. In business applications with heavy mutations, TanStack Query usually needs less hand-written code.

Does Context cause performance problems?

When the Context value changes, all components reading it re-render. With rarely changing values such as theme or language, there’s no problem. For values that change often and are read by many components, split the Context or use a store that supports selectors.

Why should I keep filters in the URL?

A filter in the URL is preserved in a shared link, works correctly with the browser’s back and forward buttons, and isn’t lost when the page is refreshed. A filter kept in a store provides none of these behaviors on its own.

Support

Contact us for support or a discovery session on this topic.

Contact form
[email protected]

Eretek Web

We build and maintain corporate websites, WordPress and CMS platforms, intranet and SharePoint portals, document management, and form and approval workflows, and keep them secure and up to date.

Knowledge Center

Other articles