Client State vs. Server Cache: The Most Consequential Boundary in the Frontend
Server data is state, but not client-owned state. Why this distinction matters, when useEffect turns into a bad cache and what a server state library takes over.
Client State vs. Server Cache: The Most Consequential Boundary in the Frontend
const [invoices, setInvoices] = useState([]);
useEffect(() => {
fetch("/api/invoices")
.then((r) => r.json())
.then(setInvoices);
}, []);
invoices is not client-owned state. It is a cached copy of data whose original lives in a database behind /api/invoices. And this cache lacks everything that makes a usable cache: a key under which a second component finds the same copy; an age after which it counts as outdated; a place where you declare it invalid after a change. As long as only one component loads and nobody changes anything, none of this shows.
The React overview distinguishes four places for state: the component, the URL, a global store and, almost in passing, the server cache. This last boundary deserves a post of its own, because in everyday work it causes the most bugs and because it is so easy to overlook.
This confusion is not a beginner’s mistake you grow out of. I see it in code reviews from people who have been writing React for years, and I made it myself for a long time. The difference sounds academic but has very practical consequences: it decides which tool you choose, how many bugs you’ll chase later and how small or large the part of the application you have to manage by hand becomes.
Two kinds of state that keep getting confused#
Let’s start with a simple question: where does the truth live? With real client state, it lives in the browser. The text in an input field, whether a menu is expanded or collapsed, which tab is currently active – all of this arises from a user interaction and exists only here. Nobody outside this browser knows or needs this value. When the component disappears, the value disappears with it, and that is perfectly fine.
With server data, it’s the other way around. The list of invoices, the user profile, the inventory – the truth about them lives in the backend, in a database, behind an API. What the browser has of it is only a copy. And copies have an unpleasant property: they go stale. The second the server sends the response, someone else may already have changed the record. The browser then holds a snapshot that looks like the truth but no longer is.
flowchart TB Frage["Where does the truth live?"] Frage --> Client["in the browser<br/>= client state"] Frage --> Server["in the backend<br/>= server data"] Client --> C1["inputs, selection,<br/>expanded menus"] Server --> S1["The browser only holds<br/>a copy – it goes stale"]
Once you ask this question, a lot falls into place differently. The counter, the form, the filter selection – client state. The loaded list, the search result, the account balance – server data, i.e. a cache. And different rules apply to a cache than to state you own yourself.
Why useEffect alone doesn’t replace a server cache#
The usual first reflex looks like this: you take useState for the data, useEffect for loading, and you’re done. Here is the pattern from the beginning again, this time with an error path and a cleanup function so that it is correct at all:
function useInvoices() {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
let active = true;
fetch("/api/invoices")
.then((r) => r.json())
.then((d) => active && setData(d))
.catch((e) => active && setError(e.message));
return () => {
active = false;
};
}, []);
return { data, error };
}
That works – for exactly one component that loads exactly once. As soon as the application grows, almost everything server data really needs is missing here. Two components showing the same list load it twice, because neither knows about the other. If you navigate away and come back, loading starts from scratch, even though the data from a moment ago would still be good enough. There is no way to renew the copy specifically after a change. And the race between an old and a new request, which the cleanup function above defuses, is only the most obvious of a whole family of problems.
An example I experienced in a similar form in a real project: a dashboard, at the top a number “open invoices: 12”, next to it a list of the same invoices. Both building blocks load their data in their own effect. Already at startup, two requests fire where one would have been enough. It gets more annoying when someone pays an invoice: the list reloads and shows eleven, the number at the top doesn’t reload and keeps showing twelve. Two copies of the same truth that drift apart – and nobody made a mistake; the code is just honestly thought through to its end. Exactly such contradictions arise inevitably when each component holds its own little cache without a shared place that knows which data is currently valid.
The real point is a different one. An effect synchronizes a component with something outside React – that is its job, and it is the right tool for that. But managing a cache is not a side concern of a single component. It is an application-wide problem: who holds which data, how old may it be, when is it renewed, who shares it? Solving this problem in every useEffect individually and by hand is roughly like writing your own little database in every function. It works, but it doesn’t scale, and every copy has its own bugs.
What a server state library takes over#
At this point, a tool built for exactly this case pays off. TanStack Query (formerly React Query) and SWR are the two widespread representatives. They share the same basic idea, which you can read from SWR’s name: stale-while-revalidate. Show the existing, possibly stale copy immediately, and renew it in the background. The user sees data right away, and the fresh data shortly afterwards.
The core is a central cache that stores data under a key. You only describe what you want and where it comes from:
import { useQuery } from "@tanstack/react-query";
function useInvoices() {
return useQuery({
queryKey: ["invoices"],
queryFn: () => fetch("/api/invoices").then((r) => r.json()),
staleTime: 30_000,
});
}
That hardly looks shorter than the useEffect, but there is a whole machinery behind it. If two components query ["invoices"] at the same time, only one request is sent – that is deduplication. If a component comes back whose data is younger than the staleTime, nothing is reloaded at all. If it is older, the library shows the old copy immediately and reloads in the background. The queryKey is more than a name: it is the identity of the data in the cache and the pivot for everything else.
The difference becomes clearest when writing. After a mutation, the cache has to learn that its copy is now wrong:
import { useMutation, useQueryClient } from "@tanstack/react-query";
function usePayInvoice() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (id) => fetch(`/api/invoices/${id}/pay`, { method: "POST" }),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["invoices"] });
},
});
}
The call invalidateQueries marks all queries under ["invoices"] as stale and reloads the active ones among them. So you no longer say “set this state” but “this server data is now unreliable, fetch it fresh”. That is exactly the right mindset for a cache: you don’t own the data, you only hold it provisionally, and after a change you declare the copy invalid. If the counter and the list use the same key family, this one invalidation updates them together. That removes a common cause of diverging displays; it doesn’t replace a guarantee, because keys, error handling and server responses still have to fit together.
If you like, you can go one step further and update the UI before the server has even responded. Via the onMutate callback, you write the expected new state directly into the cache, so the invoice appears as paid immediately; if the server then comes back with an error, the library rolls the cache back to the old state. This optimistic updating makes UIs noticeably faster, and it is only possible at all because the data lives in a central, named place and isn’t scattered across a dozen individual useState values.
flowchart LR
A["Component asks for<br/>queryKey"] --> B{"Copy in the cache<br/>and still fresh?"}
B -->|yes| C["show immediately,<br/>load nothing"]
B -->|stale| D["show old copy +<br/>reload in the background"]
D --> E["fresh data<br/>replaces the copy"]On top of that comes a whole series of small things you would otherwise have to build by hand: reloading when the window regains focus, retrying on network errors, pending and error states as a clean result instead of three separate useState calls, and tools that make the cache visible in the browser. None of this is magic – it is exactly the bookkeeping a cache needs and that is always missing in a useEffect.
SWR or TanStack Query?#
Both libraries solve the same problem but set different priorities. SWR is deliberately lean, has a narrow API and is quickly understood. You tell it how long data counts as fresh and call mutate(key) to renew it. For read-heavy UIs with simple writes, that is often exactly right, especially in the Next.js world.
TanStack Query is more extensive and gives more control: staleTime and gcTime cleanly separate how long data stays fresh and when it drops out of memory; invalidateQueries can declare entire families of queries stale at once via a prefix, which is worth a lot with nested data; and useMutation is a complete state machine with callbacks for optimistic updates. The price is a bit more weight and a few more knobs. For small, manageable cases, SWR is enough; as soon as server state complexity threatens to grow, TanStack Query pays off.
The more important point, though, runs across this choice: as soon as you treat server data as what it is – a cache with a key, an age and invalidation – all the useState-and-useEffect tinkering disappears, no matter which of the two you choose.
What is still real client state then#
Now comes the actual punchline, and it regularly surprises experienced colleagues too. If you pull server data out of state management, shockingly little remains. The cross-check is quickly done: list everything that has so far been considered “global state”, then strike it off item by item. The loaded lists? Cache. The detail data? Cache. The search result? Cache. Which filter is active, which page you are on, which record is selected? That belongs in the URL – shareable, bookmarkable, survives a reload.
What remains as client-owned state in the end is, in many applications, a small core: the text in a form while you’re still typing, UI details such as expanded sections and a few app-wide decisions – theme or shopping cart, say. For that, useState, Context or a lightweight store is often enough. Server data is state too, but it has a different source, lifetime and invalidation logic. That is exactly why it doesn’t simply belong in the same global store.
That is why I consider this boundary the most consequential in the entire frontend. It doesn’t just decide on a tool. It clears away half of state management before you even build it.
React 19: use() and Suspense#
A look ahead, because something is shifting here right now. With use() and Suspense, React 19 brings another way to bring server data into rendering: you hand a component a stable promise, use() suspends until it is fulfilled, and an enclosing <Suspense> component shows a fallback until then. The promise should come from a framework or a cache and not be created anew on every render. This moves loading and error states to the edges instead of handling them individually in every component.
This doesn’t replace a cache library – someone still has to create, cache and invalidate the promises, and that is exactly what TanStack Query and SWR now do with Suspense support. But it changes how waiting feels in the tree. I devote the post Suspense and the use Hook to this big topic of its own; here it is only a signpost, so it’s clear where React is heading.
What should stick#
If one sentence from this post should stick, it’s this one: for every value that looks like state, first ask where its truth lives. If it lives in the browser, it is real client state, and useState is right. If it lives in the backend, it is a cache, and then it needs cache rules – key, age, invalidation – and a tool that takes over this bookkeeping instead of copying it into every useEffect.
Making this distinction first and choosing the tool only afterwards prevents duplicate caches and contradictory copies. Server data is borrowed state: the client manages its presentation but owns neither its truth nor its lifecycle alone.
Further reading#
- Repository introduction-react (chapters server-access, react-hooks; recipes folder on data fetching): https://github.com/mikebild/introduction-react
- React, “You Might Not Need an Effect”: https://react.dev/learn/you-might-not-need-an-effect
- React, Synchronizing with Effects: https://react.dev/learn/synchronizing-with-effects
- TanStack Query, Query Invalidation: https://tanstack.com/query/latest/docs/framework/react/guides/query-invalidation
- SWR, official documentation: https://swr.vercel.app/
Revised and translated from German with the help of AI.