Catalog My learning Blog
Frontend Developer Course: 100 Concepts in 100 Days · Phase 7 · Lesson 61 · 6 min read

Client State vs Server State in React

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: Untangling an Overloaded Store
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Classify every piece of frontend state by where it truly lives and who owns it: server state, client UI state, URL state, form state and persisted preferences. Choose the right tool for each category, and understand why treating server data as ordinary client state causes most data bugs.

Concept Explanation

For years, frontend applications put almost everything into one global store: the current user, the list of products fetched from the API, whether a modal was open, the text in a search box. That made the store huge and the code around it repetitive, because every piece of fetched data needed loading flags, error flags, refetch logic and invalidation written by hand. The insight that changed the ecosystem was that these values are not the same kind of thing and should not be managed the same way.

Server state is data whose source of truth lives on a server. The frontend holds only a cached copy, which can become stale at any time because other users, other tabs and background jobs change the original. It is fetched asynchronously, can fail, is often shared by many components and must be kept fresh. The questions server state raises are about caching: when is a copy too old, when should it be refetched, how should components that need the same data share one request, what should happen after a mutation. Libraries such as TanStack Query, SWR, RTK Query and Apollo Client answer exactly those questions, which is why they replaced hand-written fetching in global stores.

Client state is data the frontend owns: whether a dropdown is open, which tab is selected, the contents of an unsaved draft, a multi-step wizard's progress, a theme choice. It is synchronous, always up to date and usually local to a component or a small subtree. Most of it belongs in component state with useState or useReducer, lifted only as far as needed. Truly global client state, such as a shopping cart before checkout or a notification queue, can live in context or a small store.

Three more categories deserve their own homes. URL state, such as the current page, search query, filters and sort order, belongs in the URL, so it survives reloads, can be shared and works with the back button (Day 67). Form state, values, touched fields and validation errors, is transient and best handled by the form itself or a form library (Day 68). Persisted preferences, such as a chosen language or layout, live in localStorage or on the server and are loaded into client state.

Classifying state before writing code prevents a whole family of bugs. Copying server data into a store creates a second source of truth that drifts from the cache. Storing filters only in memory breaks sharing and the back button. Lifting UI state into a global store causes needless re-renders across the app. A simple exercise for any screen is to list its data and label each item with its category and owner.

CategorySource of truthTypical toolExample
Server stateThe backendTanStack Query, SWR, framework loadersProducts, orders, current user profile
Local UI stateOne componentuseState, useReducerOpen menu, hovered row
Shared client stateThe frontend appContext or a small storeCart before checkout, toasts
URL stateThe address barRouter search paramsPage, filters, sort, selected tab
Form stateThe formNative forms, React Hook FormField values and errors
PreferencesStorage or user settingslocalStorage plus stateTheme, density, language

Worked Example: Untangling an Overloaded Store

The first version keeps server data, UI flags and filters in one store with hand-written loading logic. The refactor moves each piece to its natural home.

JavaScript
// Before: everything in one global store, server data copied and managed by hand
const useStore = create((set) => ({
  products: [], productsLoading: false, productsError: null,
  filters: { q: '', category: 'all', page: 1 },
  isCartOpen: false,
  cart: [],
  async loadProducts() {
    set({ productsLoading: true });
    try { set({ products: await api.products(useStore.getState().filters), productsLoading: false }); }
    catch (e) { set({ productsError: e, productsLoading: false }); }   // no caching, no dedupe, no refetch
  },
}));
TypeScript
// After: each category in its own home
// 1. URL state: filters in the address bar
function useProductFilters() {
  const [params, setParams] = useSearchParams();
  const filters = FiltersSchema.parse(Object.fromEntries(params));      // validated (Day 45)
  const setFilters = (next: Partial<Filters>) =>
    setParams((p) => ({ ...Object.fromEntries(p), ...next, page: String(next.page ?? 1) }));
  return [filters, setFilters] as const;
}

// 2. Server state: cached, deduplicated, refetched by the query library
function useProducts(filters: Filters) {
  return useQuery({ queryKey: ['products', filters], queryFn: () => api.products(filters) });
}

// 3. Shared client state: a tiny store for the cart
const useCart = create<CartState>((set) => ({
  items: [],
  add: (sku) => set((s) => ({ items: [...s.items, { sku, qty: 1 }] })),
}));

// 4. Local UI state: stays in the component
function CatalogPage() {
  const [filters, setFilters] = useProductFilters();
  const products = useProducts(filters);
  const [isCartOpen, setCartOpen] = useState(false);
  // render products.data, products.isPending, products.error ...
}

The refactored page lost its loading flags, error flags and loader function entirely, gained caching and request deduplication, and its filters now survive reloads and can be shared as links.

Server data lives in a query cache, URL state in the address bar, local UI state in components, shared client state in a small store, form state in the form and preferences in storage. Classifying state first prevents duplicated sources of truth.
Server data lives in a query cache, URL state in the address bar, local UI state in components, shared client state in a small store, form state in the form and preferences in storage. Classifying state first prevents duplicated sources of truth.

Real-World Examples

  • TanStack Query's documentation describes server state as remotely persisted data that you do not control or own, that can become out of date and that requires asynchronous APIs, and its creator Tanner Linsley has explained that the library was built after realizing most global state in apps was really a server cache.
  • Redux's own documentation now recommends RTK Query or another data fetching library for server data instead of writing thunks and reducers for every request, reflecting how the ecosystem separated server cache from client state.
Key TakeawaysClassify state before choosing tools. Server state is a cached copy of remote data and belongs in a query library or framework loader. Local UI state stays in components, shared client state goes in context or a small store, URL state goes in the address bar, form state stays in forms and preferences are persisted and loaded. Never copy server data into a client store.

Review Questions & Answers

Its source of truth is remote, so the frontend only holds a copy that can become stale at any time because others change the original. It is fetched asynchronously, can fail and is shared. These properties make caching, deduplication, refetching and invalidation the central concerns, which client state does not have.

It creates a second source of truth separate from the server and any cache, and every load, refresh, error and invalidation must be written by hand. The copies drift, components show stale data, and the code is repetitive.

State that should survive a reload, be shareable as a link or work with the back button: the current page of results, search queries, filters, sort order, the selected tab or the item being viewed.

Locally in the component that renders the dropdown, with useState. It is client state used by one component, and putting it in a global store would cause needless re-renders and coupling.