← Back to React, page 4

react-0071 · Medium mid

What problems does TanStack Query solve, and how do query keys, stale time and mutations with invalidation work?

TanStack Query manages server state: it fetches, caches by query key, deduplicates requests, refetches stale data in the background and tracks loading and error states. useQuery reads data identified by a key. Data is fresh for staleTime and stale afterwards. useMutation changes data on the server, and invalidateQueries marks related queries stale so they refetch and the UI updates.

Full answer

Writing fetches in effects means writing loading flags, error states, caching, retries and race protection each time. TanStack Query (formerly React Query) turns that into a few hooks and treats the API data as a cache owned by the server, not as client state.

useQuery({ queryKey: ['students'], queryFn }) runs the function and stores the result under the key. Components that use the same key share one request and one cache entry. The key is also the dependency list: ['student', id] is a different entry for each id, and changing id fetches the new one. Put every variable the function uses in the key.

The cache has two timers. staleTime says how long data counts as fresh (default 0, so data is stale at once). Stale data is still shown while a background refetch runs on triggers such as a new mount, window focus or reconnect. gcTime says how long unused entries stay in memory before removal. Raising staleTime reduces requests for data that rarely changes.

useQuery returns data, isPending, isError, error and isFetching, which separates the first load from background refreshes. Failed requests retry three times by default.

Mutations use useMutation({ mutationFn, onSuccess }). After a write, call queryClient.invalidateQueries({ queryKey: ['students'] }) so affected queries refetch. For instant feedback use optimistic updates with onMutate, rollback in onError, and invalidate in onSettled.

Client state such as an open modal does not belong in the query cache. Keep it in useState or a store. Setup requires a QueryClientProvider near the root.

The example uses an in-memory fake API so it runs without a network.

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

let students = ['Asha', 'Ravi'];
const fetchStudents = () => new Promise((resolve) => setTimeout(() => resolve([...students]), 20));
const addStudent = (name) =>
  new Promise((resolve) =>
    setTimeout(() => {
      students = [...students, name];
      resolve(name);
    }, 20)
  );

const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });

function Students() {
  const client = useQueryClient();
  const { data, isPending } = useQuery({ queryKey: ['students'], queryFn: fetchStudents, staleTime: 60000 });
  const mutation = useMutation({
    mutationFn: addStudent,
    onSuccess: () => client.invalidateQueries({ queryKey: ['students'] }),
  });

  if (isPending) return <p>Loading...</p>;

  return (
    <div>
      <ul>
        {data.map((name) => (
          <li key={name}>{name}</li>
        ))}
      </ul>
      <button onClick={() => mutation.mutate('Meera')}>Add Meera</button>
    </div>
  );
}

export default function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <Students />
    </QueryClientProvider>
  );
}

This used @tanstack/react-query with an in-memory fake API. The check waited for the first load, pressed Add Meera and waited for the refetch that invalidation triggers. Output of the run: right after mount: AshaRaviAdd Meera after the first fetch: AshaRaviAdd Meera after the mutation and refetch: AshaRaviMeeraAdd Meera

Key points

  • Treat API data as a server-owned cache keyed by queryKey. Include every variable in the key.
  • staleTime controls freshness. gcTime controls how long unused data stays cached.
  • Data is shown stale while a background refetch runs.
  • useMutation writes data and invalidateQueries refreshes related reads.
  • Do not store client-only state in the query cache.

Common mistakes

  • Leaving a variable out of the query key, so the cache returns the wrong data.
  • Storing fetched data in useState and duplicating the cache.
  • Forgetting to invalidate after a mutation.
  • Using one huge key for everything instead of structured keys.
  • Putting client-only UI state in the query cache.

Follow-ups

  • How would you implement an optimistic update with rollback?
  • What is the difference between isPending and isFetching?
  • How does TanStack Query work with server rendering and prefetching?

Tips

  • Describe the cache and key model first. It explains every behaviour after.
  • Say that server state and client state differ. It shows design thinking.
  • Mention staleTime tuning as a practical lever.