Tanstack Query: Digging Deeper With Caching, Pagination, and Further Optimization Techniques

Share
Tanstack Query: Digging Deeper With Caching, Pagination, and Further Optimization Techniques

Overview

In the first post in this series, we introduced Tanstack Query and covered the fundamentals of querying server state, handling loading and error states, and synchronizing UI updates via query invalidation.

At that point, we solved the baseline problem:

  • How do I fetch server data and keep my UI in sync without writing a bunch of code to manage side effects, re-fetching and all that fun stuff.

As your application grows, especially in live-ops or admin tooling environments you’ll quickly encounter more advanced requirements:

  • Avoiding unnecessary network requests
  • Handling large datasets efficiently
  • Paging through results without jarring UI transitions
  • Keeping cached data fresh without constantly re-fetching
  • Updating specific slices of cached data following mutations

This post digs into these more advanced, but still very common use cases.

Understanding Caching in Tanstack Query

See also: Caching in Tanstack Query

Caching is the foundation that everything else in Tanstack Query builds upon. It’s important to understand how and when data is cached. Once you do, things like pagination and query invalidation become much easier to reason about, and you will be able to take advantage of the excellent performance optimizations that Tanstack Query gives you straight away.

Cache Versus Server Truth

Tanstack Query assumes the following:

  • The server is the source of truth
  • The client cache is a synchronized snapshot

The cache exists to:

  • Reduce duplicate requests
  • Improve performance
  • Enable instant UI updates while queries re-fetch

Stale Time versus GC Time

You have some options when it comes to configuring caching behavior in Tanstack Query. Two of the most commonly used configuration options are staleTime and gcTime. These are often confused, so lets dive in a little more to understand the difference.

useQuery({
  queryKey: ['players'],
  queryFn: fetchPlayers,
  staleTime: 30000, // 30 seconds
});

In the above code snippet, staleTime controls how long the data is considered fresh. After 30 seconds, the query will be marked as stale and Tanstack Query will automatically re-fetch. ****Stale queries will automatically be re-fetched in the background when:

  • New instances of the query are mounted
  • The window is refocused (switching tabs, etc)
  • The network is reconnected
useQuery({
  queryKey: ['players'],
  queryFn: fetchPlayers,
  gcTime: 5 * 60 * 1000, // 5 minutes
});

In the above code snippet, gcTime controls how long the the query data stays in memory. If the data remains unused for 5 minutes, it will be garbage collected. In the context of your UI with this example, this would be triggered if no component in your application is using the query for 5 minutes. This is to prevent the cache from growing unbounded.

Pagination: Scaling Beyond Small Datasets

Fetching all the data at once doesn’t scale well, particularly for things like Player Lists, Audit Logs, Moderation Events, and Match History for example. Fortunately, Tanstack Query provides excellent Pagination support out of the box.

Offset Based Pagination

See also: Guide To Offset Based Pagination

We all know about our old friend offset based pagination, you’re almost certainly familiar with the following:

GET /players?offset=0&limit=5

Integrating this into our client with Tanstack Query could not be easier:

function PlayerList({ page }) {
  const { players: data, isFetching } = useQuery({
    queryKey: ['players', page],
    queryFn: () => fetchPlayers({ page }),
    keepPreviousData: true,
  });

  return (
    <div>
      {players?.map((player) => (
	        <div key={player.id}>
	          <li>{player.name}</li>
	          <li>{player.status}</li>
	          
	          <button
			        onClick={() => {
			          banPlayerMutation.mutate({
			            playerId: player.id,
			          })
			        }}
			      >
			        Ban
			      </button>
			    </div>
        ))}
       {isFetching && <Spinner />}
    </div>
  );
}

In the above code snippet, all we are doing is feeding the page parameter into the component and using it to construct the query key, as well as passing it into our query function to fetch the next page. While not pictured here, this page parameter would likely come from a pagination UI you’d build where users could select the page number at the bottom of the page.

Additionally, keepPreviousData is a nice-to-have that tells Tanstack Query to keep the old data while fetching the new page. This helps prevent your table/list from briefly flashing empty during the page transition.

Cursor Based Pagination With Infinite Queries

See also: Guide To Cursor Based Pagination

For things like logs, feeds or timelines you will almost always reach for cursor based pagination. Tanstack Query provides useInfiniteQuery out of the box for this scenario.

const { 
fetchNextPage, 
fetchPreviousPage, 
hasNextPage,
hasPreviousPage,
isFetching,
isFetchingNextPage,
isFetchingPreviousPage,
matchHistory: data,
error,
status
} = useInfiniteQuery({
  queryKey: ['matchHistory'],
  queryFn: ({ pageParam }) => fetchMatchHistory({ cursor: pageParam }),
  initialPageParam: 1,
  getNextPageParam: (lastPage) => lastPage.nextCursor,
  getPreviousPageParam: (firstPage) => firstPage.prevCursor,
});

// In your components returned JSX, you might have something like this
return status === 'pending' ? (
    <p>Loading...</p>
  ) : status === 'error' ? (
    <p>Error: {error.message}</p>
  ) : (
    <>
      {matchHistory.pages.map((history, index) => (
        <React.Fragment key={index}>
          {history.data.map((match) => (
            <p key={match.id}>{match.name}</p>
          ))}
        </React.Fragment>
      ))}
      <div>
        <button
          onClick={() => fetchNextPage()}
          disabled={!hasNextPage || isFetching}
        >
          {isFetchingNextPage
            ? 'Loading more...'
            : hasNextPage
              ? 'Load More'
              : 'Nothing more to load'}
        </button>
      </div>
      <div>{isFetching && !isFetchingNextPage ? 'Fetching...' : null}</div>
    </>
  )

In the above code snippet, we are using useInfiniteQuery to create a query to load match history data. For useInfiniteQuery, you must provide an initialPageParam. This hook returns numerous helpful pieces of data to allow you to build performant paginated UIs. For a comprehensive list of everything the useInfiniteQuery hook accepts as arguments, and returns to you, please see the official documentation here.

Query Invalidation: Being Precise, Not Noisy

In our initial post covering Tanstack Query, we used the most basic and broad query invalidation, the example used is below:

queryClient.invalidateQueries({ queryKey: ['players'] });

However, often you will find yourself wanting to be more targeted in your approach when invalidating queries so they are re-fetched across your application. For example, perhaps you don’t want to re-fetch all players in response to some user action, and instead only want to re-fetch data for a specific player. That would look like:

queryClient.invalidateQueries({
  queryKey: ['player', playerId],
});

This will prevent unnecessary re-fetches elsewhere in your application.

Query Invalidation Versus Query Re-fetch

In Tanstack Query, it’s important to understand the difference between invalidating queries and the subsequent behavior versus re-fetching a query and the subsequent behavior for that. For query invalidation, this marks the query as stale, and the query will be re-fetched at a later time. Re-fetch of stale queries occurs when:

  • The window is refocused (switching tabs, etc)
  • The network is reconnected
  • New instance of the query is mounted

For query re-fetch, this forces an immediate re-fetch. To do this, you can call:

// refetch all queries:
queryClient.refetchQueries()

// refetch all stale queries:
queryClient.refetchQueries({ stale: true })

// refetch all active queries partially matching a query key:
queryClient.refetchQueries({ queryKey: ['players'], type: 'active' })

// refetch all active queries exactly matching a query key:
queryClient.refetchQueries({
  queryKey: ['player', 1],
  type: 'active',
  exact: true,
})

Use invalidateQueries most of the time, it allows Tanstack Query to batch and optimize re-fetches.

Updating Cached Data Without Re-fetching

Sometimes you already know what the server response will be. For example, when banning a player you know you need to update only that player’s status to banned. In this case, it would be heavy handed to re-fetch the entire player list. Fortunately, Tanstack Query allows for updating the cache directly. See the below example:

queryClient.setQueryData(['players'], (oldData) => {
  if (!oldData) return oldData;

  return oldData.map(player =>
    player.id === bannedPlayerId
      ? { ...player, status: 'banned' }
      : player
  );
});

This enables:

  • Instant UI updates
  • Fewer network requests
  • Better perceived performance

You can still invalidate afterward if needed for safety.

Background Re-fetching & Window Focus

By default, Tanstack Query re-fetches stale data when:

  • The window regains focus
  • The component remounts
  • The network reconnects

For things like admin dashboards and other tooling, this is often desirable.

If not, you can opt out by passing refetchOnWindowFocus: false like below:

useQuery({
  queryKey: ['players'],
  queryFn: fetchPlayers,
  // refetchOnWindowFocus can also be set globally where you instantiate the
  // Query Client and pass it to the provider
  refetchOnWindowFocus: false,
});

Performance Patterns for Real Applications

As your application matures, several patterns will become extremely valuable, some of these are covered below:

Centralized Query Key Factories

As you begin to add more queries/keys, it can be difficult tracing them all through your application to make changes, fix issues, etc. A common pattern is to define all your query keys as a central object and then export it for use in your components, see the example below:

export const queryKeys = {
  players: ['players'] as const,
  playerProfile: (id: number) => ['playerProfile', id] as const,
  // ...rest
};

This will help reduce surface area for typos and other mistakes, and enforce some consistency.

Global Defaults via QueryClient

As previously mentioned, you will often find yourself customizing the behavior of specific queries. But sometimes, you will need to apply a specific behavior to every query in your application. For example, perhaps you want to configure the staleTime of all your queries to be 30 seconds, or you never want Tanstack Query to automatically re-fetch on window focus. For cases like this, it is advised to configure this globally by defining these where you actually create the Query Client. See the example below:

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 30000, // 30 seconds
      refetchOnWindowFocus: false,
      // ...other query options you want shared globally
    },
  },
});

Treat Mutations as First-Class Citizens

Mutations are not just POST/PUT requests. They define things like Side Effects, Cache synchronization, and UI Consistency. Tanstack Query comes with several useful helper methods for controlling re-fetches, query invalidation or optimistic updates. See the example below for a bit more information:

useMutation({
  mutationFn: banPlayer,
  onMutate: (variables, context) => {
    // Mutation is about to happen, this might be a good place 
    // to trigger a UI notification to indicate "processing" for example
  },
  onError: (error, variables, onMutateResult, context) => {
    // An error happened, perhaps we should do some kind of rollback action here
  },
  onSuccess: (data, variables, onMutateResult, context) => {
    // Trigger re-fetch, or do some invalidation, etc...
  },
  onSettled: (data, error, variables, onMutateResult, context) => {
    // Handle things regardless of the outcome
  },
})

We won’t cover mutations too in-depth here as there is a lot more to learn, but you can find much more information on mutations in the official documentation here.

Conclusion

Tanstack Query shines not just because it simplifies data fetching, but because it scales with your application as complexity increases.

With proper caching strategies, pagination patterns, and thoughtful invalidation, you can:

  • Build faster UIs
  • Reduce backend load
  • Keep server state predictable
  • Avoid entire classes of synchronization bugs

In future posts, we can go even deeper into topics like:

  • Optimistic updates
  • Query cancellation
  • Offline support
  • Error boundaries and retries
  • Integrating Tanstack Query with real-time systems

Tanstack Query isn’t just a data-fetching library, it’s a foundation for building resilient, high-performance client applications.

First post in this series covering Tanstack Query basics

Caching in Tanstack Query

Pagination in Tanstack Query

Query Invalidation