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:
setQueryDatafor optimistic updates and rollbacks. - Prefetching:
prefetchQueryon 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=300for shared public data.private, no-storefor user-specific responses.- ETags or
Last-Modifiedfor 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";23export const queryClient = new QueryClient({4 defaultOptions: { queries: { staleTime: 60_000, gcTime: 10 * 60_000, refetchOnWindowFocus: true } },5});67type Todo = { id: string; title: string; done: boolean };8const todosKey = (listId: string) => ["todos", listId] as const;910export function useTodos(listId: string) {11 return useQuery({ queryKey: todosKey(listId), queryFn: () => fetch(`/api/lists/${listId}/todos`).then((r) => r.json() as Promise<Todo[]>) });12}1314export 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 rollback23 },24 onError: (_e, _todo, ctx) => qc.setQueryData(todosKey(listId), ctx?.previous),25 onSettled: () => qc.invalidateQueries({ queryKey: todosKey(listId) }), // sync with the server26 });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.