Use useQuery, useMutation, staleTime, cache invalidation, and optimistic updates to manage server state in React applications.
0 / 5 completed
1 / 5
What does the useQuery hook from TanStack Query manage beyond a simple fetch call?
useQuery:const { data, isLoading, error } = useQuery({ queryKey: ["user", id], queryFn: () => fetchUser(id) }). The queryKey is the cache key — the same key from any component returns the cached value without a network request. TanStack Query also refetches on window focus, network reconnect, and at configurable intervals.
2 / 5
What does staleTime control in TanStack Query?
staleTime:staleTime: 5 * 60 * 1000 (5 minutes) means query results stay fresh for 5 minutes. Within that window, mounting a new component with the same query key returns the cached data with no network request. The default is 0 — every mount triggers a background refetch. Setting a longer staleTime drastically reduces unnecessary requests for stable data.
3 / 5
What is cache invalidation in TanStack Query and how is it triggered after a mutation?
Cache invalidation: after creating a post with useMutation, the posts list query is now out of date. Calling invalidateQueries marks it stale and immediately triggers a background refetch if any component is subscribed to that query. This is the primary mechanism for keeping server state synchronised after mutations.
4 / 5
What are optimistic updates in TanStack Query and how are they implemented?
Optimistic updates: in the useMutationonMutate callback, snapshot the previous cache value with queryClient.getQueryData, then set the new optimistic value with queryClient.setQueryData. In onError, restore the snapshot. In onSettled, invalidate to sync with the real server value. This gives instant UI feedback while maintaining correctness.
5 / 5
What is the QueryClient in TanStack Query and what is its scope?
QueryClient: one QueryClient instance is shared across the entire application (in SSR frameworks, one per request). It holds the in-memory cache and configuration defaults like staleTime, gcTime, and retry. Imperative methods like queryClient.prefetchQuery enable server-side data loading before rendering.