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
- No invalidation after mutation: you create a todo, but the list query is not refetched.
- Wrong cache keys:
["user"]instead of["user", userId], so different users share one entry. - Copying server data into local state:
useState(props.items)never updates when props change. - Long
staleTimewithout revalidation, or HTTP caching headers that are too aggressive. - Stale closures: intervals or listeners reading old state.
- Optimistic updates without rollback or refetch.
- Multiple tabs: another tab changed the data.
- Logout or account switch without clearing caches.
Fixes
- TanStack Query / SWR: keys that include all inputs;
invalidateQueriesormutateafter writes;refetchOnWindowFocus,refetchOnReconnect,refetchIntervalfor live data;queryClient.clear()on logout. - Frameworks: Next.js
updateTag/revalidateTagafter 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.
BroadcastChannelor thestorageevent to sync tabs.
Code example
tsx
1import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";23type Todo = { id: string; title: string };45export function useTodos(listId: string) {6 return useQuery({7 queryKey: ["todos", listId], // key includes every input8 queryFn: () => fetch(`/api/lists/${listId}/todos`).then((r) => r.json() as Promise<Todo[]>),9 staleTime: 30_000, // fresh for 30s10 refetchOnWindowFocus: true, // revalidate when the user returns11 });12}1314export 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 write20 });21}2223// On logout, drop every cached response for the previous user24export function useLogout() {25 const queryClient = useQueryClient();26 return async () => {27 await fetch("/api/logout", { method: "POST" });28 queryClient.clear();29 };30}3132// Cross-tab sync: tell other tabs to refetch33const 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.