Skip to content
Andrea Lab

ANDREA LAB / BLOG

Caching and pagination with TanStack Query in React

How to design query keys, load cursor-based pages, and keep a document browser consistent when filters or sessions change.

A document browser looks straightforward until it starts loading data from several folders. A user opens Manuals, requests a second page, and switches to Invoices while the request is still running. If the application stores both results in the same state, it can end up displaying documents from the previous folder.

In a React application with TypeScript, giving each dataset an explicit identity helps address this problem. TanStack Query provides a cache for server responses. Designing that identity and deciding when to refresh the data remain part of the application architecture.

A key describes the dataset

A query could use a key such as ['documents', workspaceId, folderId, { sort, search }]. Its values represent what determines the result. When the folder or search filter changes, the query needs to distinguish the new result from the previous one. The official guide explains how query variables participate in the key. Query keys.

Before writing the hook, describe the resource returned by the API. In this example, a folder within a workspace contains an ordered list of documents. A search term narrows that list. A cursor, meanwhile, marks where to continue within the same traversal.

A shared key factory helps the browser, a preview, and document actions refer to the same resources. It also helps identify which views need updating after an operation. Normalizing parameters keeps an empty search and a whitespace-only search from creating separate traversals for the same intent.

Keep the cursor within the traversal

With useInfiniteQuery, each page belongs to the same cache entry. initialPageParam establishes the starting point, and getNextPageParam reads the continuation cursor. Received pages are available in data.pages. This synthetic example illustrates the contract for TanStack Query v5. Infinite queries.

import { useInfiniteQuery } from '@tanstack/react-query';

type DocumentPage = {
  items: Array<{ id: string; name: string }>;
  nextCursor?: string;
};

export function useDocuments(workspaceId: string, folderId: string) {
  return useInfiniteQuery({
    queryKey: ['documents', workspaceId, folderId],
    initialPageParam: undefined as string | undefined,
    queryFn: async ({ pageParam, signal }): Promise<DocumentPage> => {
      const params = new URLSearchParams({ workspaceId, folderId });
      if (pageParam) params.set('cursor', pageParam);
      const response = await fetch(`/api/documents?${params}`, { signal });
      if (!response.ok) throw new Error('Unable to load documents');
      return response.json();
    },
    getNextPageParam: (page) => page.nextCursor ?? undefined,
  });
}

The example leaves out search and sorting to focus on the folder. When those parameters enter the request, they also belong in its identity. The API must define what a cursor means when documents are added or deleted during traversal. Stable ordering with an identifier as a tie-breaker can help, although the required consistency depends on the product.

Design the interaction during a pending request

The interface can disable Load more while a fetch is running and hide it when there is no continuation. If the second page fails, preserving the rows already loaded lets the user keep working and retry from an understandable state.

When the folder changes, the screen should reflect the new context immediately. Temporarily displaying old documents requires a clear indication that they belong to another view. In a browser where users select files for an operation, showing the new folder’s loading state until its documents arrive is easier to understand.

Decide what to update after an edit

If the server confirms a rename and returns the updated document, the application can update its cached detail. The list presents another decision. If it is sorted by name, the document may move to a different position or even a different page. Refreshing the traversal avoids having to reconstruct that distribution manually.

When the session or workspace changes, define which data can remain visible. Coordinating cleanup with navigation and pending requests reduces surprises in a shared session. The server checks permissions for every operation. The query key identifies the data retained by the interface.

Test context changes

A relevant test for this browser delays the Manuals response, switches to Invoices, and checks that the active selection contains only documents from the visible folder. Another causes the second page to fail and verifies that the first remains available. A third renames a document so its new name changes its position in the ordering.

These tests exercise product decisions that a screenshot of the initial state cannot show. When keys, cursors, and updates describe the same resource, each interaction has an outcome the user can recognize and the team can verify.