ReactMedium

Stale data issues?

Stale data means the UI shows information that no longer matches the server or the current inputs: an old list after a mutation, a previous user's data after switching accounts, values captured in closures, or cached responses that never refresh. Fix it by defining freshness rules, invalidating caches after writes, keying data by its inputs, and revalidating on focus, reconnect or intervals.

Typical causes

  1. No invalidation after mutation: you create a todo, but the list query is not refetched.
  2. Wrong cache keys: ["user"] instead of ["user", userId], so different users share one entry.
  3. Copying server data into local state: useState(props.items) never updates when props change.
  4. Long staleTime without revalidation, or HTTP caching headers that are too aggressive.
  5. Stale closures: intervals or listeners reading old state.
  6. Optimistic updates without rollback or refetch.
  7. Multiple tabs: another tab changed the data.
  8. Logout or account switch without clearing caches.

Fixes

  • TanStack Query / SWR: keys that include all inputs; invalidateQueries or mutate after writes; refetchOnWindowFocus, refetchOnReconnect, refetchInterval for live data; queryClient.clear() on logout.
  • Frameworks: Next.js updateTag/revalidateTag after mutations; React Router revalidates loaders after actions automatically.
  • Real-time: WebSockets or Server-Sent Events that update or invalidate the cache.
  • Do not mirror props in state; read props directly or reset with a key.
  • Show freshness: "Updated 2 minutes ago" and a refresh button for data where it matters.
  • BroadcastChannel or the storage event to sync tabs.

Code example

tsx
1import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
2
3type Todo = { id: string; title: string };
4
5export function useTodos(listId: string) {
6 return useQuery({
7 queryKey: ["todos", listId], // key includes every input
8 queryFn: () => fetch(`/api/lists/${listId}/todos`).then((r) => r.json() as Promise<Todo[]>),
9 staleTime: 30_000, // fresh for 30s
10 refetchOnWindowFocus: true, // revalidate when the user returns
11 });
12}
13
14export function useAddTodo(listId: string) {
15 const queryClient = useQueryClient();
16 return useMutation({
17 mutationFn: (title: string) =>
18 fetch(`/api/lists/${listId}/todos`, { method: "POST", body: JSON.stringify({ title }) }).then((r) => r.json()),
19 onSuccess: () => queryClient.invalidateQueries({ queryKey: ["todos", listId] }), // no stale list after a write
20 });
21}
22
23// On logout, drop every cached response for the previous user
24export function useLogout() {
25 const queryClient = useQueryClient();
26 return async () => {
27 await fetch("/api/logout", { method: "POST" });
28 queryClient.clear();
29 };
30}
31
32// Cross-tab sync: tell other tabs to refetch
33const channel = new BroadcastChannel("todos");
34export const notifyOtherTabs = (listId: string) => channel.postMessage({ listId });

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