Topic F8
Server state caching
Keeping server data in a per-key cache: no duplicate fetches, no repeat spinners.
Watch: when you go back to a page you just visited, the saved data shows at once, with no loading spinner.
- moving now
- being checked
- no longer used
The trouble with fetch in useEffect
- Two components needing the same data send two identical requests.
- Going back to a page you just visited means another spinner.
- After you change data (say renaming something), other components showing it don't know and keep the old value.
- You handle loading, errors, retries, cancelling on unmount, and out-of-order replies all by yourself.
Code, for programmersTanStack Query
function useUser() {
return useQuery({
queryKey: ["user"], // the cache key
queryFn: () => fetch("/api/me").then((r) => r.json()),
staleTime: 60_000, // fresh for 1 minute: no refetch at all
});
}
// header and page both call useUser(): one request, one cache entry
const { data: user, isPending } = useUser();
// after a change, tell the cache which keys are now out of date
const rename = useMutation({
mutationFn: (name) => fetch("/api/me", { method: "PATCH", body: JSON.stringify({ name }) }),
onSuccess: () => queryClient.invalidateQueries({ queryKey: ["user"] }),
});Stale-while-revalidate
The core pattern: show the old data from the cache now, then fetch the latest in the background and quietly swap it in if it differs. Users never see a spinner for data they've seen before, and still get fresh data within milliseconds. It's the same idea as the HTTP header Cache-Control: stale-while-revalidate and backend caching (Caching and LRU caches (B4) and Cache invalidation, TTL and stampedes (B5)), including the hardest problem: deciding when data is stale.
Quiz
The header and the page both call useQuery(['user']) at the same time. How many requests?
What does stale-while-revalidate mean?
After renaming through a mutation, why call invalidateQueries(['user'])?
0 of 3 answered.
Built on
Used in
No follow-up topics yet.