ReactMedium

Caching strategies?

Cache server data on the client with a library (TanStack Query, SWR, RTK Query) keyed by request parameters, tune freshness with staleTime and garbage collection with gcTime, revalidate on focus, reconnect or after mutations, and update caches optimistically. Combine this with HTTP caching (Cache-Control, ETags, CDNs) and, in frameworks, server-side caching such as Next.js "use cache".

Client cache concepts (TanStack Query terms)

  • Query keys: ["products", { category, page }]: each distinct key is a cache entry.
  • staleTime: how long data is considered fresh (no refetch). Default 0, so data is refetched on mount or focus; set 30 to 300 seconds for data that changes slowly.
  • gcTime: how long unused data stays in memory (default 5 minutes).
  • Stale-while-revalidate: show cached data immediately, refetch in the background.
  • Invalidation: queryClient.invalidateQueries({ queryKey: ["products"] }) after a mutation.
  • Direct updates: setQueryData for optimistic updates and rollbacks.
  • Prefetching: prefetchQuery on hover or in route loaders.
  • Persistence: persist the cache to IndexedDB or localStorage for offline-first apps.

HTTP and CDN

  • Cache-Control: public, max-age=60, stale-while-revalidate=300 for shared public data.
  • private, no-store for user-specific responses.
  • ETags or Last-Modified for cheap revalidation (304 responses).
  • Immutable hashed assets cached for a year.

Server and framework caches

Next.js Cache Components ("use cache", cacheLife, cacheTag), React Router Cache-Control headers from loaders, Redis in your API.

Pitfalls

  • Caching per-user data under shared keys.
  • Forgetting to invalidate after mutations.
  • Copying server data into a global store, creating two caches that drift apart.

Code example

tsx
1import { QueryClient, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
2
3export const queryClient = new QueryClient({
4 defaultOptions: { queries: { staleTime: 60_000, gcTime: 10 * 60_000, refetchOnWindowFocus: true } },
5});
6
7type Todo = { id: string; title: string; done: boolean };
8const todosKey = (listId: string) => ["todos", listId] as const;
9
10export function useTodos(listId: string) {
11 return useQuery({ queryKey: todosKey(listId), queryFn: () => fetch(`/api/lists/${listId}/todos`).then((r) => r.json() as Promise<Todo[]>) });
12}
13
14export function useToggleTodo(listId: string) {
15 const qc = useQueryClient();
16 return useMutation({
17 mutationFn: (todo: Todo) => fetch(`/api/todos/${todo.id}`, { method: "PATCH", body: JSON.stringify({ done: !todo.done }) }),
18 onMutate: async (todo) => {
19 await qc.cancelQueries({ queryKey: todosKey(listId) });
20 const previous = qc.getQueryData<Todo[]>(todosKey(listId));
21 qc.setQueryData<Todo[]>(todosKey(listId), (old = []) => old.map((t) => (t.id === todo.id ? { ...t, done: !t.done } : t)));
22 return { previous }; // for rollback
23 },
24 onError: (_e, _todo, ctx) => qc.setQueryData(todosKey(listId), ctx?.previous),
25 onSettled: () => qc.invalidateQueries({ queryKey: todosKey(listId) }), // sync with the server
26 });
27}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app