MyInternships.in

Data Fetching & APIs

React Query TanStack Basics

TanStack Query manages server state: it caches responses by key, deduplicates identical in-flight requests, refetches stale data in the background, and exposes loading and error state for you.


What is Query TanStack Basics in React?

TanStack Query manages server state: it caches responses by key, deduplicates identical in-flight requests, refetches stale data in the background, and exposes loading and error state for you.

Why Query TanStack Basics matters

Server data is not really application state — it is a cache of something that lives elsewhere. Treating it as such removes most of the useEffect plumbing from a codebase.

Query TanStack Basics example

A query replaces the whole effect
JSX
import { useQuery } from '@tanstack/react-query';

function JobList({ city }) {
  const { data, isLoading, isError, error } = useQuery({
    queryKey: ['jobs', city],
    queryFn: () => fetch(`/api/jobs?city=${city}`).then(r => r.json()),
    staleTime: 60_000,
  });

  if (isLoading) return <Skeleton />;
  if (isError) return <p>{error.message}</p>;
  return <JobGrid jobs={data} />;
}

How this works

The query key identifies the cache entry. Changing city fetches and caches a separate entry, and returning to a previous city shows the cached data instantly while revalidating in the background.

Mutations invalidate the cache

JSX
const queryClient = useQueryClient();

const { mutate } = useMutation({
  mutationFn: (jobId) => api.post('/applications', { jobId }),
  onSuccess: () => queryClient.invalidateQueries({ queryKey: ['applications'] }),
});

Key points to remember

  • staleTime controls how long data is considered fresh; gcTime how long an unused cache entry is kept.
  • Every value the query depends on must appear in the query key.
  • Mutations change data; invalidating the relevant keys refreshes what is on screen.

Common mistakes with Query TanStack Basics

  • Leaving a dependency out of the query key, so the cache serves data for the wrong parameters.
  • Copying query data into useState, which reintroduces the synchronisation problems the library removes.

React Query TanStack Basics— Interview Questions & FAQs

Do I still need Redux if I use TanStack Query?+

Often not. Query handles server state, which is most of what apps used Redux for. Keep a state library only for genuine client state such as a multi-step wizard or complex UI mode.

Related React Topics

Keep learning with these closely related lessons.

Ready to use your React skills?

Find verified React internships and fresher developer jobs across India.

Browse React Internships