← all blogs

Cutting redundant API calls in React with TanStack Query

Header Sidebar Modal Query cache 1x API
Three components, one query key, one network call.

The problem: the same GET request firing four times on one screen

Open the Network tab on a growing React or React Native app and watch what happens when a page mounts. It is surprisingly common to see the exact same endpoint fire three or four times within half a second.

Usually nobody planned it that way. It happens naturally as a codebase grows:

  • The top navbar mounts and fetches /api/me to show the avatar.
  • The sidebar mounts and fetches /api/me to check permissions.
  • A banner component mounts and fetches /api/me to see if the user finished onboarding.

When each component owns its own useEffect and fetch, none of them know that another component already asked for the exact same data two milliseconds ago. You burn mobile battery, hammer your backend, and show three different loading spinners that finish at slightly different times.

How TanStack Query solves this out of the box

TanStack Query (React Query) treats server data as a shared cache keyed by an array, not local component state.

When three components call useQuery with the exact same queryKey, TanStack Query automatically deduplicates them into a single in-flight network request. All three components subscribe to the same cache entry and update together the instant the response lands.

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

async function fetchProfile(userId: string) {
  const res = await fetch(`/api/users/${userId}`);
  if (!res.ok) throw new Error("Failed to load profile");
  return res.json();
}

export function useProfile(userId: string) {
  return useQuery({
    queryKey: ["profile", userId],
    queryFn: () => fetchProfile(userId),
    staleTime: 5 * 60 * 1000, // treat data as fresh for 5 minutes
  });
}

Now Navbar, Sidebar, and ProfileModal can all call useProfile(userId) independently. Zero prop drilling, zero manual context providers, and exactly one HTTP request.

The setting almost everyone forgets: staleTime vs gcTime

Out of the box, TanStack Query ships with staleTime: 0. That means the moment a request finishes, the cached data is immediately marked stale. Whenever a user switches browser tabs, navigates back to a screen, or opens a modal, React Query shows the cached value and quietly fires a background refetch.

That default is great for live stock tickers or chat notifications. It is wasteful for data that rarely changes every second, like user profiles, feature flags, or product details.

Keep the difference between these two timers straight:

Fresh (0 calls) Stale (bg refetch) Evicted 0s staleTime gcTime instant memory hit cached UI + silent sync
staleTime controls network refetches. gcTime controls when unused cache entries are deleted.
  • staleTime is how long cached data is considered fresh. While fresh, new components read straight from memory and make zero network calls.
  • gcTime (formerly cacheTime) is how long unused data stays in memory after the last component using it unmounts. Default is 5 minutes.

Setting staleTime to 2 to 5 minutes on slow-changing queries often cuts 30 to 50 percent of redundant GET traffic with a single line of config.

Prevent cache misses with a query key factory

One sneaky way teams lose deduplication is inconsistent keys. One file writes ["profile", id] and another file writes ["user-profile", id]. To a human they look almost identical. To the cache, they are two completely different buckets, so both fire separate requests and invalidating one does not refresh the other.

Solve it with a tiny key factory object:

export const profileKeys = {
  all: ["profile"] as const,
  detail: (userId: string) => ["profile", userId] as const,
  settings: (userId: string) => ["profile", userId, "settings"] as const,
};

Now every useQuery, prefetchQuery, and invalidateQueries call imports from profileKeys, making typos impossible and keeping mutations cleanly wired to the exact cache entries they update.

Bonus: make navigation feel instant with prefetching

Once your query keys are shared, you can warm the cache before the user even clicks. Prefetching a detail page on onMouseEnter or onFocus takes three lines and often shaves 150 to 300ms off perceived load time:

queryClient.prefetchQuery({
  queryKey: profileKeys.detail(userId),
  queryFn: () => fetchProfile(userId),
  staleTime: 5 * 60 * 1000,
});

By the time the click finishes, the data is already sitting in memory and the next view renders immediately.