Skip to the page

State management and data fetching · senior

TanStack Query: server state as a cache

TanStack Query (v5) treats server data as a cache keyed by the query key: it dedupes requests, shows cached data instantly, refetches stale data in the background, retries failures, and lets you invalidate or optimistically update entries after mutations.

The notes

What you must know

  • The query key is like a dependency array: put every variable the query function uses in it; when the key changes, it fetches the new entry.
  • staleTime (default 0) = how long data counts as fresh; fresh data is served from cache with no request. gcTime (default 5 minutes, called cacheTime before v5) = how long an unused query stays in memory.
  • Defaults: stale queries refetch on mount, window refocus and reconnect; failed queries retry 3 times with exponential backoff; results are structurally shared so unchanged data keeps its reference.
  • Mutations: after success, invalidateQueries({ queryKey: ["todos"] }) (prefix match) or setQueryData with the server response.
  • Optimistic updates: in onMutate cancel queries, snapshot getQueryData, setQueryData; restore in onError; invalidate in onSettled. Or render pending items from the mutation variables without touching the cache.
  • Do not copy query data into useState (it stops receiving updates) and do not use the cache as a client-state store.
  • RTK Query is the Redux-native alternative: endpoints, generated hooks, tag-based invalidation (providesTags/invalidatesTags), OpenAPI codegen.
  • With Server Components, initial data can come from the server; client libraries handle interactive, polling and infinite parts (prefetch + hydrate).

The red pen

Common traps: mistake → fix

  • Mistake: "staleTime and gcTime are the same thing"

    Fix: freshness vs memory lifetime.

  • Mistake: "Mirror server data into Redux slices by hand"

    Fix: you rebuild a cache without invalidation.

  • Mistake: "Set a huge gcTime to avoid refetches"

    Fix: staleTime controls refetching.

Easy to hard

Questions interviewers ask, easy to hard

  1. Defend TanStack Query (or RTK Query) over Context + useEffect for server data.
  2. Explain staleTime vs gcTime.
  3. Invalidation after a mutation: query keys vs RTK Query tags.
  4. Implement optimistic updates with rollback.
  5. In a Next.js App Router app with Server Components, do you still need it?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview