TanStack Query: Why Did My App Get Slower After Adopting It? 6 Real-World Traps to Avoid

Adopted TanStack Query but your app feels slower? Discover 6 real-world performance traps — and exactly how to fix them before they sink your project.

TanStack Query: Why Did My App Get Slower After Adopting It? 6 Real-World Traps to Avoid

You pulled TanStack Query into your stack because every developer on Twitter — sorry, X — swore it would transform your data-fetching layer. The promises were compelling: automatic caching, background refetching, server state synchronization, and a dramatic reduction in boilerplate. So you migrated your useEffect-and-useState spaghetti into clean, elegant useQuery calls.

Then something strange happened.

Your app felt slower. Network tab was busier. Your UI was flickering. Users started complaining about spinners they'd never seen before. And you, staring at your screen at 11 PM with a cold cup of coffee, started questioning every decision that led you here.

Here's the truth: TanStack Query is not magic — it's a powerful tool with a sharp edge. Most developers adopt it without understanding its default behavior, and those defaults, while sensible for many use cases, can destroy performance in others. The good news? Every single one of these traps is fixable, often in under five minutes, once you know what to look for.

Let's walk through the six most common real-world traps that slow apps down after adopting TanStack Query — and exactly how to escape each one.


Trap #1: Misunderstanding staleTime and Over-Fetching on Every Mount

This is the number-one performance killer, and it trips up nearly every developer who's new to TanStack Query.

By default, staleTime is set to 0. This means that the moment a query resolves, TanStack Query immediately considers that data "stale." The next time any component that uses that query mounts — even if it was just unmounted a millisecond ago — TanStack Query will fire a background refetch.

Imagine a dashboard with five components, each calling useQuery with the same query key. Every time the user navigates away and back, that's five potential background refetches hitting your API in rapid succession. Add a slow network or a rate-limited backend, and suddenly your "optimized" app is hammering its own server.

The fix is simple but requires intentionality:

const { data } = useQuery({
  queryKey: ['dashboard-metrics'],
  queryFn: fetchDashboardMetrics,
  staleTime: 1000 * 60 * 5, // Data stays fresh for 5 minutes
});

Setting a thoughtful staleTime based on how frequently your data actually changes is the single highest-ROI configuration change you can make. Ask yourself: does this data really need to be refetched every time a user switches tabs? For most business data — user profiles, product catalogs, settings — the answer is no.

A practical rule of thumb:

  • Real-time data (stock prices, live chat): staleTime: 0 or very low
  • Semi-static data (user profiles, preferences): staleTime: 5–10 minutes
  • Static reference data (country lists, categories): staleTime: Infinity

You can also set a global default in your QueryClient configuration to avoid repeating this on every query:

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 1000 * 60 * 5,
    },
  },
});

Trap #2: Triggering Unnecessary Re-Renders with Unstable Query Keys

This one is subtle, and it can wreak havoc on complex component trees without leaving obvious breadcrumbs in your profiler.

TanStack Query uses query keys to identify and cache data. When a query key changes, TanStack Query treats it as a brand-new query and fires a fresh fetch. The trap? Developers often construct query keys with inline objects or arrays that get recreated on every render.

Consider this innocent-looking code:

// ❌ This creates a new object reference on every render
const { data } = useQuery({
  queryKey: ['users', { role: 'admin', page: currentPage }],
  queryFn: () => fetchUsers({ role: 'admin', page: currentPage }),
});

If the parent component re-renders for any reason — a context update, an unrelated state change, a prop that changed somewhere up the tree — that inline object is a new reference. TanStack Query is smart enough to do deep comparison on query keys, so this specific case is actually safe. But many developers don't realize this and start over-engineering their key construction, or they run into issues when combining TanStack Query with memoization incorrectly.

The more dangerous version of this trap shows up when query keys include values derived from non-memoized callbacks or computed values:

// ❌ Dangerous if getFilters() returns a new reference each render
const { data } = useQuery({
  queryKey: ['products', getFilters()],
  queryFn: fetchProducts,
});

The fix: Keep your query keys simple, deterministic, and serializable. Stick to strings, numbers, and plain objects with primitive values. When filters or parameters are complex, derive them once — using useMemo if needed — before passing them into the query key.

const filters = useMemo(() => ({ category, priceRange, inStock }), [category, priceRange, inStock]);

const { data } = useQuery({
  queryKey: ['products', filters],
  queryFn: () => fetchProducts(filters),
});

Trap #3: Ignoring gcTime and Letting Your Cache Balloon

TanStack Query's cache is one of its greatest strengths — until it becomes a memory liability.

gcTime (formerly cacheTime in v4 and earlier — this was renamed in TanStack Query v5) controls how long inactive query data stays in the cache before being garbage collected. The default is 5 minutes. In most apps, this is fine. But in data-heavy applications — dashboards displaying large datasets, apps that paginate through hundreds of records, or long-running single-page apps — this cache can grow surprisingly large.

Consider an e-commerce admin panel where a user browses through 50 pages of orders. Each page query gets cached for 5 minutes. If the dataset per page is large, your in-memory footprint climbs fast. Users on lower-end devices or with limited RAM will start experiencing sluggishness that has nothing to do with network speed.

The fix is to tune gcTime appropriately:

const { data } = useQuery({
  queryKey: ['orders', page],
  queryFn: () => fetchOrders(page),
  gcTime: 1000 * 60 * 2, // Only keep inactive data for 2 minutes
});

For paginated or infinite scroll implementations, also consider using placeholderData with keepPreviousData behavior (which in v5 is now placeholderData: keepPreviousData) rather than caching every single page indefinitely.

Additionally, for truly large datasets, consider whether you need to cache all the data at all — sometimes fetching fresh data on demand is cheaper than holding it all in memory.


Trap #4: Abusing enabled Flags and Creating Waterfall Fetches

Dependent queries are a legitimate and common pattern. You need a user ID before you can fetch their orders. You need a session token before you can hit a protected endpoint. TanStack Query's enabled option handles this gracefully — in theory.

The trap happens when developers chain too many dependent queries naively, creating deep waterfalls that delay the final data the user actually cares about.

// ❌ Waterfall: each query waits for the previous one
const { data: user } = useQuery({ queryKey: ['user'], queryFn: fetchUser });
const { data: team } = useQuery({ queryKey: ['team', user?.teamId], queryFn: () => fetchTeam(user.teamId), enabled: !!user });
const { data: projects } = useQuery({ queryKey: ['projects', team?.id], queryFn: () => fetchProjects(team.id), enabled: !!team });

In this scenario, the user might wait through three sequential round trips before seeing any project data. On a 100ms latency connection, that's 300ms of unnecessary waiting — before you've even counted render time.

The fix: Rethink your data architecture. Where possible:

  • Parallelize independent queries using multiple useQuery calls side by side
  • Use useQueries for dynamic parallel fetching
  • Move dependent data fetching to your backend — an API endpoint that returns a user, their team, and their projects in one call is almost always faster than three sequential client-side fetches
  • Leverage React Server Components (if you're on Next.js 13+ or a compatible framework) to resolve data dependencies on the server before the page reaches the client

The 2024–2025 trend toward combining TanStack Query with RSC patterns is worth exploring here. TanStack Query v5 has excellent integration patterns for hydrating server-fetched data into the client cache, eliminating waterfalls entirely for initial page loads.


Trap #5: Refetch Intervals That Multiply Across Component Instances

refetchInterval is a powerful feature for real-time data needs. Set it on a query and TanStack Query will automatically poll your API on a schedule. It's elegant — until you realize that the same query with the same key, mounted in multiple components simultaneously, will only poll once. That's the intended behavior.

The trap? When developers don't use a shared query key — often due to a small naming inconsistency or a misconfigured query factory — each component instance ends up with its own polling loop.

// Component A
useQuery({ queryKey: ['notifications'], queryFn: fetchNotifications, refetchInterval: 5000 });

// Component B — slightly different key, now polling independently
useQuery({ queryKey: ['notification'], queryFn: fetchNotifications, refetchInterval: 5000 }); // ← typo!

That typo just doubled your polling frequency. In a large component tree with shared data, this mistake can multiply dramatically, causing cascading API requests that your backend was never designed to handle.

The fix: Use query key factories — a pattern recommended in TanStack Query's official documentation and widely adopted in the community:

// queryKeys.js
export const notificationKeys = {
  all: ['notifications'],
  list: () => [...notificationKeys.all, 'list'],
  detail: (id) => [...notificationKeys.all, 'detail', id],
};

// Usage — consistent everywhere
useQuery({ queryKey: notificationKeys.list(), queryFn: fetchNotifications, refetchInterval: 5000 });

A centralized key factory eliminates typos, makes refactoring trivial, and gives you a single source of truth for your entire cache.


Trap #6: Skipping Suspense and Error Boundary Optimization

TanStack Query's integration with React Suspense has matured significantly, particularly in v5 with the introduction of useSuspenseQuery. But many teams adopt TanStack Query and never touch Suspense, opting instead for manual isLoading and isError state checks in every component.

This isn't a correctness problem — it works. The performance and user experience problem is more subtle. When you manage loading states manually at the component level, you often end up with cascading loading spinners: nested components that each show their own loader, creating a visually jarring, janky experience that feels slower even when the actual fetch time hasn't changed.

Additionally, without proper error boundary integration, failed queries can leave components in broken states that are hard to recover from without a full page refresh.

The modern approach:

// Use useSuspenseQuery for cleaner loading orchestration
const { data } = useSuspenseQuery({
  queryKey: ['dashboard'],
  queryFn: fetchDashboard,
});

Wrap your component tree in a <Suspense> boundary with a thoughtful fallback, and pair it with an <ErrorBoundary> for resilient error handling. This lets React coordinate loading states across the entire subtree, eliminating the spinner cascade and making your UI feel snappier — even if the underlying fetch times are identical.

The 2025 ecosystem has embraced this pattern enthusiastically, with frameworks like TanStack Start (now in stable release) building Suspense-first data loading into their foundations.


Conclusion: TanStack Query Is a Multiplier — Make Sure It's Multiplying the Right Things

TanStack Query doesn't slow apps down. Misconfigured TanStack Query does — and there's an important difference.

The library ships with defaults designed to work for a broad range of use cases. But "broad range" is not "every situation," and the gap between defaults and your specific application's needs is exactly where performance problems are born. The six traps we've covered — aggressive stale times, unstable query keys, unchecked cache growth, fetch waterfalls, polling multiplication, and unoptimized Suspense integration — account for the vast majority of real-world slowdowns teams report after adoption.

The good news is that every fix is achievable in a focused afternoon of refactoring. Start by auditing your staleTime configuration. Then move to query key consistency. Tackle the rest incrementally. Use React DevTools and TanStack Query's own DevTools (the @tanstack/react-query-devtools package is invaluable) to watch your cache behavior in real time.

Your next step: Open your codebase right now and search for useQuery. If you don't see staleTime on at least your most frequently called queries, that's your first fix — and it might be the only one you need.

TanStack Query is one of the most capable data-fetching libraries in the JavaScript ecosystem. Used thoughtfully, it doesn't just match your old useEffect approach — it leaves it in the dust. The goal isn't to avoid the tool. It's to master it.

No comments

Comments

Loading comments…

Contact support