The RK Times
← All posts TanStack Query in Production: Gotchas, Mistakes and a Review Checklist

TanStack Query in Production: Gotchas, Mistakes and a Review Checklist

By Romaan · Nov 16, 2026 · 17 min read · 11 views

I have shipped TanStack Query (the library formerly known as React Query) in four production React apps now: two internal dashboards, one customer-facing portal and one fairly chatty real-time-ish admin tool. It has removed more code from those projects than any other library I've added. It has also produced some of the more confusing bugs I've chased, nearly all of them my own fault for misunderstanding what the library is doing for me.

This post is the write-up I wish I'd had on day one: what TanStack Query is actually for, the patterns that held up, the gotchas that bit me, the mistakes I keep catching in pull requests, and the checklist I use when I review TanStack Query code. All examples use TypeScript and TanStack Query v5.


The one idea that makes everything else click

TanStack Query is not a data-fetching library. It doesn't fetch anything. You hand it a function that returns a promise, and it manages what comes back. Its job is server state: data that lives somewhere else, that someone else can change, and that is out of date the moment you receive it.

Once I started thinking of it as a cache with opinions about staleness rather than "a nicer useEffect + fetch", most of my confusion went away. Every behaviour that surprised me (the refetch when I tab back into the browser, the request firing twice, the data that "won't update") is the cache doing exactly what it was configured to do.

Here's the before/after that sells it to most teams. The hand-rolled version:

// The version everyone writes first
function UserCard({ userId }: { userId: string }) {
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);

  useEffect(() => {
    let cancelled = false;
    setLoading(true);
    fetch(`/api/users/${userId}`)
      .then((r) => r.json())
      .then((data) => { if (!cancelled) setUser(data); })
      .catch((e) => { if (!cancelled) setError(e); })
      .finally(() => { if (!cancelled) setLoading(false); });
    return () => { cancelled = true; };
  }, [userId]);

  if (loading) return <Spinner />;
  if (error) return <ErrorBox error={error} />;
  return <div>{user?.name}</div>;
}

That's already more careful than most (it handles the race when userId changes), and it still has no caching, no deduplication if two components want the same user, no retry, and no way to refresh it after a mutation elsewhere. The TanStack Query version:

function UserCard({ userId }: { userId: string }) {
  const { data, isPending, isError, error } = useQuery({
    queryKey: ['users', userId],
    queryFn: () => fetchUser(userId),
  });

  if (isPending) return <Spinner />;
  if (isError) return <ErrorBox error={error} />;
  return <div>{data.name}</div>; // data is User here, not User | undefined
}

Note that last comment. After you've narrowed on isPending and isError, TypeScript knows data is defined. That narrowing only works if you destructure the status flags and check them; it's one reason I prefer checking isPending over checking !data.


Setup I now use on every project

1. A typed fetch wrapper that actually throws

TanStack Query decides whether a query failed by whether your queryFn throws or rejects. fetch does not reject on a 404 or 500. It resolves happily with ok: false. I have seen this exact bug in three codebases: error UI that never appears, because the "error" was parsed as data.

// api/http.ts
export class HttpError extends Error {
  constructor(
    public readonly status: number,
    public readonly body: unknown,
  ) {
    super(`HTTP ${status}`);
    this.name = 'HttpError';
  }
}

export async function http<T>(
  input: string,
  init?: RequestInit & { signal?: AbortSignal },
): Promise<T> {
  const res = await fetch(input, {
    ...init,
    headers: { 'Content-Type': 'application/json', ...init?.headers },
  });
  if (!res.ok) {
    const body = await res.json().catch(() => null);
    throw new HttpError(res.status, body);
  }
  // 204 No Content has no body to parse
  return (res.status === 204 ? undefined : await res.json()) as T;
}

Then tell TypeScript what errors look like globally, so you don't have to cast error everywhere:

// react-query.d.ts
import '@tanstack/react-query';
import type { HttpError } from './api/http';

declare module '@tanstack/react-query' {
  interface Register {
    defaultError: HttpError;
  }
}

2. A QueryClient with deliberate defaults

// main.tsx
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 30_000, // treat data as fresh for 30s
      retry: (failureCount, error) => {
        // never retry client errors; a 404 won't fix itself
        if (error instanceof HttpError && error.status < 500) return false;
        return failureCount < 2;
      },
    },
  },
});

createRoot(document.getElementById('root')!).render(
  <QueryClientProvider client={queryClient}>
    <App />
    <ReactQueryDevtools initialIsOpen={false} />
  </QueryClientProvider>,
);

Two things worth calling out. First, the client is created once, outside any component. Second, staleTime is the setting that matters most, and its default is 0. More on that below.

3. Query keys and options live together, in one place per feature

This is the single pattern that paid off most. Instead of scattering useQuery({ queryKey: [...], queryFn }) through components, each feature exports its keys and query definitions using the queryOptions helper:

// features/todos/queries.ts
import { queryOptions, keepPreviousData } from '@tanstack/react-query';

export type TodoFilters = { status: 'all' | 'open' | 'done'; page: number };

export const todoKeys = {
  all: ['todos'] as const,
  lists: () => [...todoKeys.all, 'list'] as const,
  list: (filters: TodoFilters) => [...todoKeys.lists(), filters] as const,
  details: () => [...todoKeys.all, 'detail'] as const,
  detail: (id: string) => [...todoKeys.details(), id] as const,
};

export const todoQueries = {
  list: (filters: TodoFilters) =>
    queryOptions({
      queryKey: todoKeys.list(filters),
      queryFn: ({ signal }) =>
        http<Page<Todo>>(`/api/todos?${new URLSearchParams({
          status: filters.status,
          page: String(filters.page),
        })}`, { signal }),
      placeholderData: keepPreviousData, // no spinner flash when paging
    }),

  detail: (id: string) =>
    queryOptions({
      queryKey: todoKeys.detail(id),
      queryFn: ({ signal }) => http<Todo>(`/api/todos/${id}`, { signal }),
      staleTime: 60_000,
    }),
};

Components then become boring, which is exactly what you want:

const { data } = useQuery(todoQueries.detail(id));

// ...and elsewhere, with the same types and the same key, guaranteed:
await queryClient.prefetchQuery(todoQueries.detail(id));
const cached = queryClient.getQueryData(todoQueries.detail(id).queryKey); // typed as Todo | undefined

Why this matters: query keys are just arrays, and a typo in one (['todo', id] vs ['todos', id]) creates a separate cache entry that silently never gets invalidated. Centralising keys makes that kind of bug structurally hard. The hierarchical shape also makes invalidation precise: todoKeys.lists() hits every list regardless of filters, todoKeys.all hits everything to do with todos.

Passing signal through to fetch is a small thing that's easy to skip. It lets TanStack Query cancel in-flight requests when a component unmounts or a key changes, which matters a lot for search-as-you-type.


Mutations, invalidation and optimistic updates

The simple, correct default after a write is: invalidate, don't hand-edit the cache.

export function useCreateTodo() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (input: NewTodo) =>
      http<Todo>('/api/todos', { method: 'POST', body: JSON.stringify(input) }),
    onSettled: () =>
      // returning the promise keeps the mutation "pending" until the refetch lands
      queryClient.invalidateQueries({ queryKey: todoKeys.lists() }),
  });
}

Note the return (here implicit in the arrow function). If you don't return the invalidation promise, isPending on the mutation flips to false before the list has refreshed, and users see a brief flash of stale data. Small, but people notice.

When the UI genuinely needs to feel instant (toggles, likes, reordering), go optimistic. This is the full shape, and every part of it matters:

export function useToggleTodo(filters: TodoFilters) {
  const queryClient = useQueryClient();
  const listKey = todoKeys.list(filters);

  return useMutation({
    mutationFn: (todo: Todo) =>
      http<Todo>(`/api/todos/${todo.id}`, {
        method: 'PATCH',
        body: JSON.stringify({ done: !todo.done }),
      }),

    onMutate: async (todo) => {
      // 1. stop any in-flight refetch from overwriting our optimistic value
      await queryClient.cancelQueries({ queryKey: listKey });
      // 2. snapshot for rollback
      const previous = queryClient.getQueryData<Page<Todo>>(listKey);
      // 3. write the optimistic value, immutably
      queryClient.setQueryData<Page<Todo>>(listKey, (old) =>
        old && {
          ...old,
          items: old.items.map((t) => (t.id === todo.id ? { ...t, done: !t.done } : t)),
        },
      );
      return { previous };
    },

    onError: (_err, _todo, context) => {
      // 4. roll back
      if (context?.previous) queryClient.setQueryData(listKey, context.previous);
    },

    onSettled: () =>
      // 5. always resync with the server, success or failure
      queryClient.invalidateQueries({ queryKey: todoKeys.lists() }),
  });
}

The step people drop is #1, cancelQueries. Without it, a background refetch that started before the click can resolve after your optimistic write and stomp it, so the checkbox flicks back for a moment. It's a race that only shows up on a slow network, which means it shows up in production and never on your laptop.

Step 3 has its own trap: setQueryData must return a new object. Mutate old in place and nothing re-renders, because TanStack Query compares by reference.

A pragmatic note: optimistic updates are a lot of code to get right. For most forms, plain invalidation plus a disabled button while isPending is the better trade. If you just need the new value to show in one place while it's saving, v5 also lets you render mutation.variables directly in the UI, without touching the cache at all.


Gotchas that cost me real time

"Why does it refetch every time I switch tabs?"

Because the default staleTime is 0. Data is considered stale the instant it arrives, and stale data gets refetched on mount, on window focus and on network reconnect. That's a reasonable default for a library that can't know your data, but it's almost never what you want for, say, a list of countries or the current user's profile.

My mental model: staleTime answers "how long can I trust this?", gcTime answers "how long do I keep it around after nobody's looking?". Set staleTime per query based on how often the data really changes. Don't paper over the refetching by switching off refetchOnWindowFocus globally; that just hides stale data from you.

"It fires twice in development"

React 18+ StrictMode mounts, unmounts and remounts components in development. TanStack Query deduplicates most of this, but if you see two network requests, check whether you're in StrictMode before you go hunting. It doesn't happen in a production build.

The QueryClient created inside a component

// ❌ a brand-new, empty cache on every render
function App() {
  const queryClient = new QueryClient();
  return <QueryClientProvider client={queryClient}>...</QueryClientProvider>;
}

// ✅ module scope for SPAs, or useState for SSR (one client per request)
function App() {
  const [queryClient] = useState(() => new QueryClient());
  return <QueryClientProvider client={queryClient}>...</QueryClientProvider>;
}

The symptom is "caching doesn't work" and an infinite fetch loop in the worst case. For SSR (Next.js and friends), a module-level client is worse: it's shared between requests, which means one user's data can leak into another's render.

onSuccess on useQuery is gone

v5 removed onSuccess, onError and onSettled from useQuery. They still exist on useMutation. The removal annoyed people, but the reasoning is sound: a query callback fires per observer, not per fetch, and it doesn't fire at all when data comes from the cache. Code that did onSuccess: (data) => setFormValues(data) was already subtly broken. Derive from data during render, or put toast-on-error logic on the QueryCache's global onError.

Unstable select functions

// runs on every render, because the function identity changes each time
const { data: openCount } = useQuery({
  ...todoQueries.list(filters),
  select: (page) => page.items.filter((t) => !t.done).length,
});

// stable: defined once
const selectOpenCount = (page: Page<Todo>) => page.items.filter((t) => !t.done).length;
const { data: openCount } = useQuery({ ...todoQueries.list(filters), select: selectOpenCount });

For cheap transforms it doesn't matter. For an expensive transform over thousands of rows, it does. Pull it out of the component or wrap it in useCallback.

Dependent queries and enabled

const { data: user } = useQuery(userQueries.me());

const { data: projects } = useQuery({
  queryKey: ['projects', user?.orgId],
  queryFn: () => fetchProjects(user!.orgId), // ← the "!" is a lie we told TypeScript
  enabled: !!user?.orgId,
});

This works, but the non-null assertion is fragile; someone refactors enabled and you get a request to /orgs/undefined/projects. v5's skipToken lets TypeScript enforce it for you:

import { skipToken } from '@tanstack/react-query';

const orgId = user?.orgId;
const { data: projects } = useQuery({
  queryKey: ['projects', orgId],
  queryFn: orgId ? () => fetchProjects(orgId) : skipToken,
});

One more enabled trap: a disabled query that has never run reports isPending: true. If you render a spinner on isPending, a query waiting on a user's input will show a spinner forever. Use isLoading (which is isPending && isFetching) for "actually loading right now".


Common mistakes I see in code review

1. Copying query data into useState

// ❌ two sources of truth; local copy never sees background updates
const { data } = useQuery(todoQueries.detail(id));
const [todo, setTodo] = useState<Todo | undefined>();
useEffect(() => { if (data) setTodo(data); }, [data]);

This is the most common one by a distance, and it throws away the main thing you installed the library for. If you're reading the data, read data directly. The legitimate exception is a form you're editing: initialise the form once from the server value (mount the form after data loads and pass it as defaultValues), then submit via a mutation. Don't sync it on every change.

2. Putting client state in TanStack Query (or server state in Redux)

Modal open/closed, the selected tab, a multi-step wizard's draft: none of these are server state. Using setQueryData as a global store "because it's there" works until a refetch or a garbage collection quietly resets your UI. The reverse mistake (fetching into Redux/Zustand and re-implementing loading flags and staleness by hand) is how you end up with the hand-rolled version from the top of this post, times fifty.

3. Variables used in queryFn but missing from queryKey

// ❌ changing `page` won't refetch; all pages share one cache entry
useQuery({ queryKey: ['todos'], queryFn: () => fetchTodos(page) });

// ✅
useQuery({ queryKey: ['todos', { page }], queryFn: () => fetchTodos(page) });

Think of the key as the dependency array of your query. Anything the queryFn reads must be in it. Install @tanstack/eslint-plugin-query; its exhaustive-deps rule catches this automatically and it's the cheapest win on this list.

4. Using useQuery for writes

A POST in a queryFn will be retried, re-run on window focus and deduplicated. None of those are things you want for "charge the customer's card". Writes go in useMutation.

5. Invalidating everything

queryClient.invalidateQueries() with no filter refetches every active query on the page. It "fixes" the stale-data bug and quietly turns one save into fifteen requests. Invalidate the narrowest key that covers what changed; that's what the key factory is for.

6. One giant query per page

A usePageData() hook that fetches the user, their projects, notifications and settings in one Promise.all means one slow endpoint blocks everything, one failure fails everything, and invalidating notifications refetches the lot. Separate queries are cheap, cache independently, and render progressively.

7. Ignoring the error state

Plenty of components handle isPending, then go straight to data.map(...). TypeScript will complain about this if your types are honest, which is a good reason to keep them honest and not reach for data!.


Where TanStack Query is great

  • CRUD-heavy apps and dashboards. The bread and butter. Caching, dedup and background refresh replace a pile of boilerplate per screen.
  • Snappy navigation. Going back to a page you've seen shows cached data immediately while it revalidates. Prefetching on hover (queryClient.prefetchQuery) makes detail pages feel instant.
  • Pagination and infinite scroll. keepPreviousData and useInfiniteQuery handle the fiddly bits (cursor tracking, avoiding layout flashes) that people usually get wrong by hand.
  • Consistency across the page. Two components showing the same resource share one cache entry, so they can't disagree.
  • Debuggability. The Devtools panel showing every key, its status and its data is one of the best debugging tools in the React ecosystem. Use it before you add a console.log.
  • Not coupled to your transport. REST, GraphQL, gRPC-web, IndexedDB, a Web Worker: anything that returns a promise works.

Where it's a poor fit, or adds friction

  • Truly real-time data. For a live chat or a trading ticker, a WebSocket subscription is the source of truth and the "stale/fresh" model doesn't map well. You can push socket messages into the cache with setQueryData, and I've done it, but at that point you're using TanStack Query as a store with extra steps.
  • Purely client-side state. Use useState, context, or a small store. See mistake #2.
  • Very small apps. A page with one fetch on load doesn't need a cache. It's ~13 kB gzipped; not huge, but not free either.
  • When your framework already owns data loading. If you're all-in on React Server Components or framework loaders (Next.js App Router, Remix/React Router loaders), much of what TanStack Query does is already handled on the server. It still earns its place for client-side interactivity, mutations and polling, but evaluate it rather than adding it out of habit.
  • The learning curve is real. staleTime vs gcTime, isPending vs isLoading vs isFetching, when callbacks fire: juniors routinely misread these. Budget time for the team to learn the model, not just the API.
  • Cache bugs are "spooky". When data is wrong, it's often because of a key mismatch or an invalidation that never happened, which is harder to trace than a direct fetch. Conventions (key factories, the ESLint plugin) are what keep this manageable.

Testing

Two rules make TanStack Query tests deterministic: a fresh QueryClient per test (otherwise cached data leaks between tests), and retry: false (otherwise a failing request is retried with exponential backoff and your test times out instead of asserting the error UI).

// test/utils.tsx
export function renderWithClient(ui: React.ReactElement) {
  const client = new QueryClient({
    defaultOptions: { queries: { retry: false, gcTime: Infinity } },
  });
  return {
    client,
    ...render(<QueryClientProvider client={client}>{ui}</QueryClientProvider>),
  };
}

// UserCard.test.tsx — network mocked with MSW
it('shows an error when the user is missing', async () => {
  server.use(http.get('/api/users/42', () => new HttpResponse(null, { status: 404 })));
  renderWithClient(<UserCard userId="42" />);
  expect(await screen.findByRole('alert')).toHaveTextContent(/not found/i);
});

Mock the network (MSW is my default), not the useQuery hook. Mocking the hook tests that you can call a mock; mocking the network tests your keys, your fetch wrapper and your error handling together.


How I review TanStack Query code

This is the checklist I actually run through on a PR that touches data fetching. Most of it can be scanned in a couple of minutes.

Query keys

  • Does every value the queryFn reads appear in the queryKey? (The ESLint plugin should be enforcing this; if it's disabled on a line, ask why.)
  • Are keys coming from the feature's key factory, or are there hand-written arrays that could drift?
  • Are keys serialisable? No class instances, functions or Date objects that should be strings.

Query functions

  • Does the queryFn throw on non-2xx? Look for raw fetch(...).then(r => r.json()).
  • Is the signal passed through, especially for search and filter queries?
  • Is the response type real (validated, or at least a shared API type) rather than an as any?

Configuration

  • Has someone thought about staleTime for this data, or is it inheriting 0 by accident?
  • Any refetchOnWindowFocus: false or staleTime: Infinity needs a reason in the PR description.
  • Is retry sensible for this endpoint (no retrying 4xx, no retrying non-idempotent work)?

Component usage

  • Are all three states handled: pending, error, success? Is the empty-list case handled separately from pending?
  • Is isPending used where isLoading was meant (disabled queries)?
  • Any query data copied into useState or a store? Any useEffect watching data?
  • Is select stable if it's expensive?
  • Any data! non-null assertions that should be status checks or skipToken?

Mutations

  • Are writes in useMutation, not useQuery?
  • Does the mutation invalidate (or update) every key whose data it changes, and only those?
  • Is the invalidation promise returned from onSettled/onSuccess when the UI depends on it?
  • For optimistic updates: cancelQueries first, immutable setQueryData, a snapshot returned from onMutate, rollback in onError, and invalidation in onSettled. If any of the five is missing, ask.
  • Is the submit button disabled while isPending, so a double-click doesn't double-submit?

Tests

  • Fresh QueryClient per test, retry: false.
  • Is there a test for the error path, not just the happy path?

Wrapping up

TanStack Query is the rare library that makes code both shorter and more correct, provided you accept its model: server data is a cache, the cache is keyed, and staleness is something you configure rather than fight. Nearly every bug I've had with it came from treating it like a fancier useEffect, and nearly every one of those was preventable with three habits:

  1. Keep keys and query definitions in a factory per feature, built with queryOptions.
  2. Make your fetch wrapper throw, and type your errors globally.
  3. Choose staleTime on purpose, and turn on the ESLint plugin.

Get those in place on day one and most of the gotchas above simply don't come up. If you've hit a TanStack Query gotcha that isn't on this list, leave it in the comments; I'm sure I haven't found them all yet.


Comments (0)

Be the first to comment.