State vs server cache

useState/useReducer for UI state, TanStack Query/SWR for server state — stale-while-revalidate, invalidation, optimistic updates with rollback.

About 24 min read3-question knowledge check

The mental model

The mistake almost every intermediate React developer makes is treating **server data as if it were UI state**. They fetch a list of orders in useEffect, drop it into useState, and then spend the rest of the feature manually keeping that copy in sync — refetching after every mutation, adding loading booleans, wiring error flags, guarding against the component unmounting mid-request. That is re-implementing a cache badly, one feature at a time.

The mental model that fixes it: there are two fundamentally different kinds of state, and they want different tools.

  • **UI state** is state your app *owns*. Is the modal open? What is the current tab? What has the user typed but not submitted? There is exactly one source of truth (the component), it is synchronous, and nobody else can change it behind your back. useState/useReducer are exactly right.
  • Server state is a *cache of data the app does not own.* The truth lives in a database on another machine. Your copy is stale the moment you fetch it; someone else can change the real value; the same data appears in three components at once; and it needs loading, error, and refetch semantics. This is not state — it is a cache, and caches have hard, well-studied problems (invalidation, staleness, deduplication) that a library should solve, not you.

The analogy: UI state is your **scratchpad** — yours, private, instantly editable. Server state is a **printout of a shared spreadsheet** — a snapshot of something living elsewhere that other people are editing right now. You would not manage the printout with a useState; you would want something that knows when to reprint, that doesn't reprint the same page twice if two people ask at once, and that shows you the last printout while a fresh one is on its way. That "something" is a server-cache library: TanStack Query or SWR. Their whole job is stale-while-revalidate — show the cached copy immediately, silently refetch, swap in the fresh copy when it arrives.

The full lesson continues with 15 more sections
  • Deep dive
  • Internal architecture
  • Real-world use cases
  • Best practices
  • Common mistakes
  • Performance
  • Security
  • Production troubleshooting
  • Advantages & disadvantages
  • Alternatives
  • Interview expectations
  • Interview questions
  • Facts to remember
  • Cheat sheet
  • Quick revision