Skip to content

Interview PrepState and data · Core

TanStack Query ​

47. What is TanStack Query, and what problems does it solve? ​

The short answer

TanStack Query, formerly React Query, is a library for server state: data that lives on a server and is fetched over the network. You give it a key and a function that fetches; it handles loading and error states, caches the result, de-duplicates identical requests from different components, refetches in the background when data becomes stale or the window regains focus, retries failures, and lets you invalidate or update the cache after a change. It removes most hand-written fetching code from components.

tsx
import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query'

const queryClient = new QueryClient()                                      // (1)

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <OrdersPage />
    </QueryClientProvider>
  )
}

function OrdersPage() {
  const { data, isPending, isError, error, isFetching } = useQuery({
    queryKey: ['orders', { status: 'open' }],                              // (2)
    queryFn: async ({ signal }) => {                                       // (3)
      const res = await fetch('/api/orders?status=open', { signal })
      if (!res.ok) throw new Error(`orders failed: ${res.status}`)         // (4)
      return (await res.json()) as Order[]
    },
  })

  if (isPending) return <Spinner />                                        // (5)
  if (isError) return <p>Could not load orders: {error.message}</p>
  return (
    <>
      {isFetching && <small>Refreshing…</small>}                           {/* (6) */}
      <OrderTable orders={data} />
    </>
  )
}
  1. One client holds the cache for the whole app.
  2. The query key identifies this data in the cache (question 48).
  3. The fetch function gets an AbortSignal, so leaving the page cancels the request.
  4. Throwing marks the query as failed. fetch does not throw on 404 or 500 by itself, so check res.ok.
  5. isPending means there is no data yet.
  6. isFetching means a request is running, including background refreshes while old data is already shown.

What you no longer write by hand:

ConcernHandled by
Loading and error flagsisPending, isError
Two components asking for the same dataOne shared request
Stale data after returning to the tabrefetchOnWindowFocus
Flaky networkAutomatic retries, three by default in the browser
Showing old data while new data loadsStale-while-revalidate (question 49)
Updating lists after a changeinvalidateQueries (question 50)
Race conditions between requestsResults stored by key (question 38)

Wrap queries in custom hooks so components stay simple, and key and fetcher live in one place:

ts
export const ordersQuery = (status: string) => queryOptions({
  queryKey: ['orders', { status }],
  queryFn: () => api.get<Order[]>(`/orders?status=${status}`),
})
export const useOrders = (status: string) => useQuery(ordersQuery(status))

48. How do query keys and caching work? ​

The short answer

A query key is an array that uniquely names a piece of server data, such as ['order', 42] or ['orders', { status: 'open', page: 2 }]. The cache is a map from keys to data: every useQuery with the same key shares one cache entry and one request. Any variable the fetch function uses must be in the key, so different inputs get different entries. Keys are hierarchical, so invalidating ['orders'] also affects every key that starts with 'orders'.

tsx
useQuery({ queryKey: ['orders'], queryFn: fetchAllOrders })
useQuery({ queryKey: ['orders', { status: 'open' }], queryFn: () => fetchOrders('open') })
useQuery({ queryKey: ['order', orderId], queryFn: () => fetchOrder(orderId) })     // (1)

queryClient.invalidateQueries({ queryKey: ['orders'] })                             // (2)
  1. The orderId is in the key, so order 41 and order 42 are cached separately. Leaving it out would show order 41's data while viewing order 42.
  2. Prefix matching: this marks both ['orders'] and ['orders', { status: 'open' }] as stale, but not ['order', 42].

Rules for good keys:

RuleWhy
Include every input the fetcher usesDifferent inputs must not share a cache entry
Put general parts first['orders', 'list', filters] lets you invalidate all orders at once
Objects inside keys are fineKeys are compared by content, not reference, so property order does not matter
Use a key factoryorderKeys.detail(id) avoids typos across files
ts
export const orderKeys = {
  all: ['orders'] as const,
  lists: () => [...orderKeys.all, 'list'] as const,
  list: (filters: { status?: string; page?: number }) => [...orderKeys.lists(), filters] as const,
  detail: (id: string) => [...orderKeys.all, 'detail', id] as const,
}

49. What is the difference between staleTime and gcTime? ​

The short answer

staleTime is how long fetched data counts as fresh. While fresh, TanStack Query serves it from the cache without refetching; once stale, it still shows it immediately but refetches in the background on the next trigger, such as a component mounting or the window regaining focus. The default is 0, so data is stale straight away. gcTime, which used to be called cacheTime, is how long unused data stays in memory after no component is using it, five minutes by default, before it is deleted.

① fetcheddata arrives② freshserved, no refetch③ staleshown, then refreshed④ removedout of memorylasts staleTimedefault 0gcTime after the last user leavesdefault 5 minutesa background refetch makes it fresh again
Fresh, stale, gone. ① Data arrives. ② For staleTime, it is served as is. ③ After that it is still shown immediately, but refreshed in the background when something triggers it. ④ Once nothing uses it for gcTime, it is deleted.
tsx
useQuery({
  queryKey: ['categories'],
  queryFn: fetchCategories,
  staleTime: 10 * 60 * 1000,          // (1) categories rarely change: fresh for 10 minutes
})

useQuery({
  queryKey: ['stock', sku],
  queryFn: () => fetchStock(sku),
  staleTime: 0,                       // (2) stock changes constantly
  refetchInterval: 15_000,            // (3)
})
  1. A long staleTime for slow-changing data cuts requests dramatically.
  2. Zero means every new mount or focus refetches, but the cached value is still shown instantly.
  3. Polling for live data.
staleTimegcTime
ControlsWhen to refetchWhen to forget
AppliesWhile data is in useAfter no component uses it
Default05 minutes
Increase it whenData changes rarelyUsers often come back to the same screens

A common surprise: "my data refetches every time I switch tabs". That is staleTime: 0 plus refetchOnWindowFocus: true. Raise staleTime for that query rather than turning off focus refetching everywhere.

50. How do mutations and cache invalidation work? ​

The short answer

A mutation is a change on the server, such as creating, updating or deleting something, run with useMutation, which gives you mutate, a pending state and error handling. After it succeeds, the cached queries showing that data are out of date, so you either invalidate them with queryClient.invalidateQueries, which marks them stale and refetches the ones on screen, or write the returned data straight into the cache with setQueryData. Invalidation is simpler and safer; direct updates save a request.

tsx
function CancelOrderButton({ orderId }: { orderId: string }) {
  const queryClient = useQueryClient()

  const cancel = useMutation({
    mutationFn: (id: string) => api.post<Order>(`/orders/${id}/cancel`),     // (1)
    onSuccess: (updated) => {
      queryClient.setQueryData(orderKeys.detail(updated.id), updated)         // (2)
      queryClient.invalidateQueries({ queryKey: orderKeys.lists() })          // (3)
    },
  })

  return (
    <button disabled={cancel.isPending} onClick={() => cancel.mutate(orderId)}>   {/* (4) */}
      {cancel.isPending ? 'Cancelling…' : 'Cancel order'}
      {cancel.isError && <span role="alert"> Failed: {cancel.error.message}</span>}
    </button>
  )
}
  1. The function that changes data on the server.
  2. Write the returned order directly into its detail cache entry, so the details screen updates without a request.
  3. Invalidate every order list, whatever its filters, because the cancelled order's status changed in them. Lists on screen refetch now; others refetch next time they are used.
  4. mutate starts it; isPending disables the button to prevent double submits.
ApproachProsCons
invalidateQueriesAlways correct: data comes from the serverOne more request
setQueryData from the responseInstant, no extra requestYou must update every affected entry correctly
Optimistic updateFeels instant even before the server answersNeeds rollback on failure (question 51)

mutateAsync returns a promise, for when the component must wait, for example to navigate after creating an order.

51. How do you do optimistic updates? ​

The short answer

An optimistic update changes the UI as if the request has already succeeded, then sends the request, and undoes the change if it fails. With TanStack Query, in onMutate you cancel in-flight fetches for that data, save the current cached value, and write the expected new value into the cache. In onError you restore the saved value, and in onSettled you invalidate, so the cache ends up matching the server either way. Use it for actions that almost always succeed, such as liking, toggling or reordering.

tsx
function useToggleFavourite() {
  const queryClient = useQueryClient()
  const key = ['favourites']

  return useMutation({
    mutationFn: (sku: string) => api.post(`/favourites/${sku}/toggle`),
    onMutate: async (sku) => {
      await queryClient.cancelQueries({ queryKey: key })                       // (1)
      const previous = queryClient.getQueryData<string[]>(key)                 // (2)
      queryClient.setQueryData<string[]>(key, (old = []) =>
        old.includes(sku) ? old.filter((s) => s !== sku) : [...old, sku])      // (3)
      return { previous }                                                      // (4)
    },
    onError: (_err, _sku, context) => {
      queryClient.setQueryData(key, context?.previous)                         // (5)
      toast('Could not update favourites')
    },
    onSettled: () => queryClient.invalidateQueries({ queryKey: key }),         // (6)
  })
}
  1. Cancel in-flight fetches, so an older response cannot land after the optimistic change and overwrite it.
  2. Save a snapshot for rollback.
  3. Write the expected result immediately; every component showing favourites updates at once.
  4. Pass the snapshot to the other callbacks through the context value.
  5. Roll back if the server refuses, and tell the user.
  6. Re-sync with the server whether it worked or not.

A simpler v5 option for one screen: show mutation.variables in the UI while isPending, without touching the cache, for example rendering a new comment in grey until it is saved.

When not to be optimistic: payments, stock reservations and anything where showing success before it happened would mislead the user.

52. How do you handle pagination and infinite scroll with TanStack Query? ​

The short answer

For numbered pages, put the page number in the query key, so each page is cached separately, and use placeholderData: keepPreviousData so the old page stays on screen while the next one loads, instead of a spinner. For infinite scroll, use useInfiniteQuery: it stores a list of pages, passes a pageParam such as a cursor to your fetch function, and asks getNextPageParam how to get the next one; you call fetchNextPage when the user nears the bottom.

Numbered pages:

tsx
function OrderPages() {
  const [page, setPage] = useState(1)
  const { data, isPlaceholderData } = useQuery({
    queryKey: ['orders', 'list', { page }],                       // (1)
    queryFn: () => api.get<{ items: Order[]; totalPages: number }>(`/orders?page=${page}`),
    placeholderData: keepPreviousData,                            // (2)
  })
  return (
    <>
      <OrderTable orders={data?.items ?? []} dimmed={isPlaceholderData} />
      <button disabled={page === 1} onClick={() => setPage((p) => p - 1)}>Previous</button>
      <button disabled={isPlaceholderData || page === data?.totalPages} onClick={() => setPage((p) => p + 1)}>Next</button>
    </>
  )
}
  1. The page is part of the key, so going back to page 1 is instant from the cache.
  2. Keep showing the previous page while the next loads.

Infinite scroll with a cursor:

tsx
function ActivityFeed() {
  const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useInfiniteQuery({
    queryKey: ['activity'],
    queryFn: ({ pageParam }) => api.get<{ items: Activity[]; nextCursor: string | null }>(
      `/activity?cursor=${pageParam ?? ''}`),
    initialPageParam: null as string | null,                     // (1)
    getNextPageParam: (lastPage) => lastPage.nextCursor,         // (2)
  })

  const items = data?.pages.flatMap((p) => p.items) ?? []        // (3)
  return (
    <>
      {items.map((a) => <ActivityRow key={a.id} activity={a} />)}
      {hasNextPage && (
        <button onClick={() => fetchNextPage()} disabled={isFetchingNextPage}>
          {isFetchingNextPage ? 'Loading…' : 'Load more'}
        </button>
      )}
    </>
  )
}
  1. The first request's parameter: no cursor.
  2. How to get the next page. Returning null or undefined means there are no more pages, which sets hasNextPage to false.
  3. Pages are stored separately, so flatten them for display.

Trigger fetchNextPage automatically with an IntersectionObserver on a sentinel element at the bottom, and virtualise if the list grows very long (question 28). Cursor-based paging on the server is covered in the API design module.

53. How do you prefetch data and avoid loading spinners? ​

The short answer

Start fetching before the component needs the data. Call queryClient.prefetchQuery when the user shows intent, such as hovering over a link, or in a route loader before the page renders, so the data is already cached when the component asks for it. Use initialData or placeholderData from a list you already have to show a detail screen instantly. And make sure related requests start in parallel rather than one after another.

tsx
function OrderLink({ id }: { id: string }) {
  const queryClient = useQueryClient()
  const prefetch = () => queryClient.prefetchQuery({                        // (1)
    queryKey: orderKeys.detail(id),
    queryFn: () => fetchOrder(id),
    staleTime: 30_000,
  })
  return <Link to={`/orders/${id}`} onMouseEnter={prefetch} onFocus={prefetch}>Order {id}</Link>
}

// in a React Router loader: fetch before the route renders
export const orderLoader = (queryClient: QueryClient) => ({ params }: { params: { id: string } }) =>
  queryClient.ensureQueryData({ queryKey: orderKeys.detail(params.id), queryFn: () => fetchOrder(params.id) })   // (2)

function OrderDetails({ id }: { id: string }) {
  const queryClient = useQueryClient()
  const { data } = useQuery({
    queryKey: orderKeys.detail(id),
    queryFn: () => fetchOrder(id),
    placeholderData: () =>                                                   // (3)
      queryClient.getQueryData<Order[]>(orderKeys.lists())?.find((o) => o.id === id),
  })
  return data ? <OrderView order={data} /> : <Spinner />
}
  1. Prefetch on hover or keyboard focus. By the time the user clicks, the request has usually finished.
  2. ensureQueryData in a loader returns cached data or fetches it, so the route renders with data already there.
  3. Placeholder from the list: show the summary you already have while the full order loads.

Avoiding request waterfalls: a parent that fetches, then renders a child that fetches, then a grandchild that fetches, makes the user wait for three round trips in a row. Start independent queries together, with several useQuery calls in one component, useQueries, or by prefetching them all in the route loader.

With Suspense, useSuspenseQuery lets a component assume data exists; the nearest <Suspense> boundary shows the loading state (question 26).

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
React, Vite & Next.js
React
State and data
Vite
Next.js
Other topics
Nothing picked yet