TanStack Query vs SWR: which should you use?

IntermediateState management interview questionBy , updated 24 November 2026

Short answer

Both are stale-while-revalidate caches for server data: they show cached data at once, refetch in the background and share one request between components. SWR is the smaller, simpler React-only hook with few knobs. TanStack Query is larger and more configurable, with staleness control, garbage collection, query cancellation, official devtools and adapters for several frameworks. Choose SWR for mostly read-heavy React screens, TanStack Query when mutations, caching rules or other frameworks matter.

Versions compared

This page compares TanStack Query v5 (@tanstack/react-query 5.108 in November 2026) with SWR 2 (swr 2.5.1). If you have not used TanStack Query before, start with what TanStack Query is and why to use it. Older tutorials use v4 syntax such as useQuery(key, fn) and cacheTime; staleTime and gcTime covers the rename.

The same feature in both

SWR takes a key and a fetcher. The key is passed to the fetcher, and null skips the request:

import useSWR from "swr";

const fetcher = async (url: string) => {
  const res = await fetch(url);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
};

function Todos() {
  const { data, error, isLoading, isValidating } = useSWR<Todo[]>("/api/todos", fetcher);
  // ...
}

TanStack Query takes one options object and needs a QueryClientProvider at the root:

import { useQuery } from "@tanstack/react-query";

function Todos() {
  const { data, error, isPending, isFetching } = useQuery({
    queryKey: ["todos"],
    queryFn: ({ signal }) => fetchJson<Todo[]>("/api/todos", { signal }),
  });
  // ...
}

The shapes map closely: SWR's isLoading is TanStack's isPending (no data yet), and isValidating is isFetching (any request running, including background ones). SWR works without a provider; SWRConfig is optional and sets a shared fetcher and options. TanStack's queryFn receives an AbortSignal, so a request is cancelled when the query is no longer needed. SWR's fetcher gets only the key.

Where they differ

SWR 2 TanStack Query v5
Frameworks React only React, Preact, Vue, Solid, Svelte and Angular adapters
Call shape useSWR(key, fetcher, options) useQuery({ queryKey, queryFn, ...options })
Staleness No staleTime: cached data revalidates on mount, focus and reconnect; useSWRImmutable never revalidates staleTime, 0 by default; only stale data refetches
Deduplication Same key within dedupingInterval (2 s) shares one request In-flight requests for the same key are shared
Focus refetch On, throttled by focusThrottleInterval (5 s) On, for stale queries
Unused data Stays in the cache; no automatic garbage collection Removed after gcTime, 5 minutes by default
Retries Retries errors with backoff (shouldRetryOnError) 3 retries with backoff in the browser
Writes mutate() and useSWRMutation useMutation plus queryClient methods
Invalidation mutate(key), or a filter function over keys invalidateQueries by key prefix or predicate
Infinite lists useSWRInfinite with size and setSize useInfiniteQuery with page params, both directions, maxPages
Devtools Community swr-devtools extension Official @tanstack/react-query-devtools
Extras Subscriptions (useSWRSubscription), preload, tiny API select, structural sharing, persisters, offline mutations, useQueries

On size, Bundlephobia (checked November 2026) reports about 5.7 kB minified and gzipped for swr 2.5.1 and about 13.4 kB for @tanstack/react-query 5.108.4. Treat that as "SWR is roughly half the size", not an exact cost to your app.

Caching defaults in practice

The biggest behavioural difference is staleness. In TanStack Query you decide how long data stays fresh. Fresh data is served from cache without a request on mount or focus, so staleTime: 60_000 turns most remounts into zero requests.

SWR has no such setting. Every new mount of a key revalidates, unless another request for that key happened within the last two seconds (dedupingInterval). To stop revalidation for a key you turn off revalidateIfStale, revalidateOnFocus and revalidateOnReconnect, or use useSWRImmutable, which fetches once for the life of the cache. There is no middle ground like "fresh for one minute".

SWR also keeps every key it has seen until the page unloads or you clear it (unload() was added in 2.5). TanStack Query drops inactive queries after gcTime, which matters for apps that page through many keys.

Mutations and optimistic updates

SWR's mutate updates the cache for a key, and its options build an optimistic update in one call:

const { data, mutate } = useSWR<Todo[]>("/api/todos", fetcher);

async function toggle(todo: Todo) {
  await mutate(patchTodo(todo.id, { done: !todo.done }), {
    optimisticData: (current = []) =>
      current.map((t) => (t.id === todo.id ? { ...t, done: !t.done } : t)),
    rollbackOnError: true, // the default
    populateCache: false, // the PATCH returns one todo, not the list
    revalidate: true, // refetch the list afterwards
  });
}

useSWRMutation from swr/mutation is the hook form: it never runs on its own, you call trigger(arg), and it tracks isMutating. Its fetcher gets (key, { arg }).

TanStack Query separates the steps. useMutation gives mutate, isPending, variables and lifecycle callbacks; you write the optimistic value in onMutate, restore a snapshot in onError and call invalidateQueries in onSettled. It is more code, but each step is explicit, and you can also skip the cache and render variables while the mutation is pending. Optimistic updates with TanStack Query shows both patterns, and building a TanStack-style useMutation has you implement the lifecycle.

Invalidation differs too. TanStack matches by key prefix, so ["todos"] covers ["todos", { page: 2 }]. SWR keys are usually URL strings, so you pass a filter function to the global mutate from useSWRConfig(): mutate((key) => typeof key === "string" && key.startsWith("/api/todos")).

Infinite queries

useSWRInfinite from swr/infinite calls getKey(pageIndex, previousPageData) for each page and returns data as an array of pages plus size and setSize. "Load more" is setSize(size + 1), and returning null from getKey ends the list. By default only the first page revalidates.

useInfiniteQuery works with page params instead: you give initialPageParam and getNextPageParam (and optionally getPreviousPageParam), then call fetchNextPage and read hasNextPage. It supports loading in both directions and maxPages to cap memory. Building a useInfiniteQuery practises that model.

SSR, Next.js App Router and Suspense

In the App Router, both libraries' hooks run only in Client Components.

  • TanStack Query: create a QueryClient in a Server Component, await queryClient.prefetchQuery(...), and wrap the client part in <HydrationBoundary state={dehydrate(queryClient)}>. Set a staleTime above 0 so the client does not refetch straight after hydration. @tanstack/react-query-next-experimental streams useSuspenseQuery results from the server.
  • SWR: pass server-fetched data to <SWRConfig value={{ fallback: { "/api/todos": todos } }}>. SWR 2.5 also added an experimental cacheData option: a Server Component calls preload(key, fetcher) and passes the result to SWRConfig, so the client does not repeat the first request.

For Suspense, TanStack Query has dedicated hooks (useSuspenseQuery, useSuspenseInfiniteQuery, useSuspenseQueries) whose data is never undefined. SWR uses the suspense: true option; its docs warn that it causes waterfalls easily and that on the server you must provide fallbackData or fallback. In both, errors go to an error boundary. Data fetching in the Next.js App Router explains when a client cache is needed at all.

How to choose

  • A React app that mostly reads data and refreshes it: SWR. Less API, smaller bundle, and its defaults (revalidate on mount and focus) suit dashboards and feeds.
  • Many mutations, optimistic UI and shared lists: TanStack Query. Prefix invalidation, explicit mutation lifecycles and useMutationState scale better.
  • You need control over freshness or memory: TanStack Query, for staleTime and gcTime.
  • Vue, Solid, Svelte, Angular or several frameworks: TanStack Query; SWR is React only.
  • Offline support or persisting the cache: TanStack Query has persisters and paused mutations that resume when back online.
  • The app already uses Redux Toolkit: neither; see RTK Query vs TanStack Query.

What interviewers listen for

  • That both are server-state caches built on stale-while-revalidate, and you can name the shared ideas: keys, deduplication, background revalidation and cache updates after writes.
  • The default that differs most: SWR revalidates cached data on every mount and focus, while TanStack Query skips fresh data once you set staleTime.
  • How each handles a mutation end to end, including rollback.
  • A choice tied to the app's needs, not to which library is newer.

Follow-up questions interviewers ask

What does stale-while-revalidate mean here?

Show the cached value immediately, then fetch in the background and replace it if it changed. The name comes from the HTTP Cache-Control extension; an HTTP cache with stale-while-revalidate builds the HTTP version.

Can SWR do what staleTime does?

Only partly. dedupingInterval stops repeat requests for a couple of seconds, and immutable mode stops them for good, but there is no "fresh for N minutes" setting.

Which one cancels requests?

TanStack Query passes an AbortSignal to queryFn and aborts it when the query is no longer used or when you call cancelQueries. SWR does not cancel requests; a response for an old key is simply ignored.

Do both deduplicate requests?

Yes. Components that ask for the same key at the same time share one request. SWR also dedupes for two seconds after a request, while TanStack Query relies on staleTime to avoid refetching fresh data.

Can you use them together?

You can, but two caches for the same data drift apart. Pick one per app, and migrate key by key if you switch.

Mistakes to avoid

  • Writing a fetcher that does not throw on 4xx and 5xx, so errors look like data in either library

  • Leaving variables out of the key, so different inputs share one cache entry

  • Expecting SWR to stop refetching after a mutation-free minute; it has no staleTime

  • Leaving TanStack's staleTime at 0 for server-rendered data, causing an immediate refetch after hydration

  • Using v4 TanStack Query syntax with v5

Practise it in code

Interviewers rarely stop at the definition. These questions open in an editor with tests.

  1. Build a mini React Query: QueryClient, useQuery, prefix invalidation and garbage collectionHard60 min
  2. Implement useQuery() with caching, retries, and stale dataMedium45 min
  3. Build a TanStack Query-style useMutation(): lifecycle callbacks, optimistic updates, rollback and invalidationMedium50 min
  4. Build a TanStack Query-style useInfiniteQuery(): page params, fetchNextPage, hasNextPage, maxPages and refetchMedium50 min
  5. Implement an HTTP cache with ETag validation, stale-while-revalidate, and request deduplicationHard75 minFree
  6. Build a data browser over a remote API: a shared cache, deduplicated requests, prefetch and no stale dataMedium45 min