الانتقال إلى المحتوى
FrontendState Management· 6 دقائق للقراءة

Server Data Isn't Client State: Stop Hand-Rolling API Caches

Data from an API is a copy of something other people change. It needs keys, freshness and invalidation, not just useState and a loading flag.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • React 19
محتويات المقال

An admin dashboard loads the orders list when it mounts and keeps it in state, with loading and error flags next to it. A support lead refunds an order, and her screen shows "refunded" because her handler patches the list. Her colleague has had the dashboard open since the morning. An hour later, his screen still says "paid", and he tells the customer the refund hasn't gone through. Nothing in his app knew the data had changed, because nothing ever asked the server again.

The common misconception

The belief: data from an API is state like any other. Fetch it in an Effect, put it in useState or a global store, add isLoading and error flags, and you're done. If two screens need it, move it to the store.

It's a reasonable starting point, and it works for the demo. The response really is a value in memory, React renders it like any other state, and stores are good at sharing values. What the belief misses is where the truth lives. A form draft exists only in your app, so the state is the truth. Orders exist on the server, so your state is only a copy, and a copy brings problems that client state never has.

What actually happens

Client state is yours; server state is a copy

TanStack Query's docs describe what makes server state different. It's persisted remotely, in a place you may not control. You read and write it through asynchronous APIs that can fail. Ownership is shared, so other people can change it without your knowledge. And your copy can become out of date if you're not careful. None of that is true of a dropdown's isOpen.

Redux Toolkit's docs reach the same conclusion from the other side: the React community has come to see data fetching and caching as a different set of concerns from state management. You can cache server data in a store, they say, but the needs are different enough to deserve a purpose-built tool.

What a copy needs that useState doesn't give

Put server data in plain state and every job below becomes code you write, test and maintain:

  • A key. The cached data is the answer to a question, like "orders with status paid", so the cache needs one entry per question.
  • Freshness. Something has to decide when the copy is out of date and fetch it again, ideally in the background while the old data stays on screen.
  • Deduplication. When the header badge and the page ask the same question, they should share one request and one answer.
  • Invalidation. After your own write, every cached answer it affects has to be refreshed.
  • Lifetime. Answers nobody reads anymore should eventually be dropped.

On top of those come the loading and error states per question, retries, and the response races covered in the article on fetching in Effects. The hand-rolled version usually implements the first fetch and stops there:

TSX OrdersPage.tsx
import { useEffect, useState } from "react";export function OrdersPage({ status }: { status: string }) {  const [orders, setOrders] = useState<Order[]>([]);  const [loading, setLoading] = useState(true);  const [error, setError] = useState<Error | null>(null);  useEffect(() => {    // Fetched once per status, then never refreshed    setLoading(true);    fetchOrders(status)      .then(setOrders)      .catch(setError)      .finally(() => setLoading(false));  }, [status]);  if (loading) return <Spinner />;  if (error) return <ErrorView error={error} />;  return <OrderList orders={orders} />;}

What a server-state cache does for you

The right-hand version is shorter, but the real difference is the behavior that comes with it. The queryKey names the question, so every component that asks ["orders", status] reads the same cache entry. TanStack Query's documented defaults then handle freshness: cached data counts as stale right away, and a stale query refetches in the background when a new component using it mounts, when the window regains focus, and when the network reconnects. Failed queries are retried 3 times with exponential backoff before the error reaches the UI, and queries nobody uses are garbage collected after 5 minutes.

The colleague's dashboard now refreshes the moment he switches back to its tab. For your own writes, invalidation does the rest: after the refund succeeds, queryClient.invalidateQueries({ queryKey: ["orders"] }) marks every query whose key starts with "orders" as stale and refetches the ones on screen. Nobody patches the list by hand.

TanStack Query is one example. RTK Query, which ships with Redux Toolkit, generates hooks per endpoint that fetch on mount, refetch when their arguments change and manage how long cached data lives. React's docs list TanStack Query, SWR and React Router 6.4+ as popular options, and recommend your framework's built-in data fetching first if you use one.

Client stateServer state
Who owns itYour appThe server, and others can change it
How you read itSynchronously, always worksAsynchronously, can fail
Is your copy current?AlwaysOnly as of the last fetch
What it needsuseState, a reducer or a storeA cache with keys, refetching and invalidation
ExamplesDrafts, open panels, the themeOrders, products, the user's profile

How to apply it in your project

  1. Sort your state into two pilesList what's in your stores and useState calls. Anything filled from an API response, plus the loading and error flags around it, is server state.
  2. Choose one server-state toolUse your framework's data fetching if it has one, or a cache library. If you already use Redux Toolkit, RTK Query is in the same package.
  3. Give every query a key with its parametersInclude everything the request depends on, like ["orders", status], so different questions never share an answer.
  4. Invalidate after writesAfter a mutation succeeds, invalidate the affected keys instead of editing cached lists by hand.

Key takeaways

  • Client state belongs to your app; server state is a copy of data that others change, and it starts aging on arrival.
  • A copy needs keys, freshness, deduplication, invalidation and a lifetime; useState and a loading flag give none.
  • Server-state tools give you those as defaults, like refetching on focus and reconnect, retries and cleanup.
  • Keep drafts, filters and toggles in client state; read server data from the cache, and invalidate it after writes.

📚 المصادر

  1. Overview — TanStack Query React Docs
  2. Important Defaults — TanStack Query React Docs
  3. Query Invalidation — TanStack Query React Docs
  4. RTK Query Overview — Redux Toolkit
  5. Synchronizing with Effects — React

التعليقات (0)