Tech Interview RoomStudy guides

React Ecosystem

How do you fetch and cache server data with TanStack Query?

Intermediate · 2 min read · Lesson 2 of 7 in React Ecosystem

TanStack Query (formerly React Query) manages server state: data owned by the backend that the UI caches. It handles caching, deduplication of identical requests, background refetching, retries, pagination, and optimistic updates.

Core ideas

  • Query keys identify data: ['orders', { status, page }]. Same key → same cache entry; components using it share one request.
  • useQuery({ queryKey, queryFn }) returns data, isPending, isError, error, isFetching.
  • staleTime: how long data counts as fresh (no refetch); gcTime: how long unused data stays in memory.
  • Automatic refetch on window focus, reconnect and mount (when stale).
  • useMutation for writes; after success, invalidate related queries (queryClient.invalidateQueries({ queryKey: ['orders'] })) or update the cache directly.
  • Optimistic updates: update the cache immediately in onMutate, roll back in onError.
  • useInfiniteQuery for "load more" and infinite scroll; useSuspenseQuery for Suspense; prefetching on hover or in route loaders.

Why not useEffect + useState?

Hand-written fetching misses race conditions, caching, deduplication, retries, stale-while-revalidate and cache invalidation; TanStack Query solves these consistently.

Example

tsx
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';

type Order = { id: string; status: 'NEW' | 'PAID'; total: number };

const fetchOrders = async (status: string): Promise<Order[]> => {
  const res = await fetch(`/api/orders?status=${status}`);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
};

export function Orders({ status }: { status: string }) {
  const qc = useQueryClient();
  const { data = [], isPending, isError, error } = useQuery({
    queryKey: ['orders', { status }],
    queryFn: () => fetchOrders(status),
    staleTime: 60_000,
  });

  const markPaid = useMutation({
    mutationFn: (id: string) => fetch(`/api/orders/${id}/pay`, { method: 'POST' }),
    onMutate: async id => {                                   // optimistic update
      await qc.cancelQueries({ queryKey: ['orders'] });
      const previous = qc.getQueryData<Order[]>(['orders', { status }]);
      qc.setQueryData<Order[]>(['orders', { status }], old => old?.map(o => (o.id === id ? { ...o, status: 'PAID' } : o)));
      return { previous };
    },
    onError: (_e, _id, ctx) => qc.setQueryData(['orders', { status }], ctx?.previous),
    onSettled: () => qc.invalidateQueries({ queryKey: ['orders'] }),
  });

  if (isPending) return <p>Loading…</p>;
  if (isError) return <p role="alert">{error.message}</p>;
  return (
    <ul>
      {data.map(o => (
        <li key={o.id}>
          {o.id} · ₹{o.total} · {o.status}
          {o.status === 'NEW' && <button onClick={() => markPaid.mutate(o.id)}>Mark paid</button>}
        </li>
      ))}
    </ul>
  );
}

Follow-up questions interviewers ask

Try answering each one before you open it.

isPending vs isFetching?

isPending is true when there is no cached data yet (first load: show a skeleton). isFetching is true whenever a request is running, including background refetches while old data is displayed (show a small spinner, not a skeleton).