TanStack Query caching
You configure cached queries and page fetching around the API client so the restaurant screen can load more data and refresh when the app reconnects.
Learning outcomes
- Distinguish server state from client state and manage server data with TanStack Query.
- Design query keys that identify every input and understand cache freshness and retention.
- Configure cursor-based infinite queries using
initialPageParamandgetNextPageParam. - Connect query focus and network events to React Native, and control retries and polling.
- Invalidate cached queries after mutations so screens display server-confirmed data.
The restaurant screen needs to load restaurants near the Week 2 seed point, 28.46 latitude and 77.03 longitude, twenty at a time. Customers expect the list to retain its contents during refreshes and to update when they return to the app after being offline. The menu screen also needs to reuse cached data when the configurator opens.
These requirements involve more than making a request inside useEffect. You need to decide who owns the data, how the cache identifies it, and which phone events should trigger another request.
Server state and client state
The app holds two different kinds of state.
Server state belongs to the Go API. Restaurants, menus, prices and orders are examples. The app holds a local copy, but the server remains the source of truth. That copy can become stale, and multiple screens may need the same data.
Client state belongs to the app. The selected size in the configurator, the contents of an unsaved form and the cart are examples. Other clients do not own these values.
TanStack Query manages server state. It fetches data, stores it in a cache, deduplicates matching requests and exposes loading and error states. It can also refetch data when it becomes stale.
You know the general query model from React on the web. The same library works in React Native, but the browser events it normally relies on are not available in the same way.
The cart has a different lifetime requirement. It must survive application restarts, so the app uses Zustand with persistent storage for that client state.
Query keys and cache identity
A query key identifies one query's cached data. It is an array, and every input that changes the requested data belongs in that array.
The restaurant request depends on latitude, longitude and radius. Its key therefore includes all three:
const queryKey = [
"restaurants",
near.lat,
near.lng,
near.radiusKm,
];Two components using the same key share the same cache entry. TanStack Query can also deduplicate matching requests, so two screens requesting the same data do not need separate network calls.
The coordinates matter. Suppose the customer changes their delivery location but the query key remains ["restaurants"]. The new request and the previous request now compete for the same cache entry.
That can show restaurants from the previous location or mix pages belonging to different locations.
A query key should describe the complete identity of the requested data, not merely the endpoint name.
Hierarchical keys
Query keys also support prefix matching.
For example, an orders list and an individual order can use:
["orders"]
["orders", 42]
["orders", 57]The first key identifies the list. The other two identify individual orders.
Invalidating the ["orders"] prefix can mark the list and its detail queries stale together. You do not need to maintain a separate list of every order id.
Query states
A query has a status and a fetch state. These describe different things.
In TanStack Query v5, the main status flags are:
isPending: there is no resolved data yet. Use this for the initial loading state.isError: the latest query execution failed.isSuccess: the query has successful data.
Fetching has separate flags:
isFetching: a request is currently running.isRefetching: an existing query is fetching again, rather than performing its initial load.isFetchingNextPage: an infinite query is fetching another page.
A query can have existing data and an error at the same time. For example, the initial restaurant request succeeds, but a later background refetch fails. The previous data remains available.
This distinction changes what the customer sees.
If the initial request fails and there is no data, display a full-screen error with a retry action. If a background refetch fails, keep the existing restaurants visible.
The screen should make its decision using both the query status and the available data.
For pull-to-refresh, the spinner should represent a refetch rather than every possible fetch. The restaurant list also fetches next pages, and that operation has its own loading indicator.
Cursor-based pagination
Week 2's GET /v1/restaurants endpoint uses keyset pagination. Each response contains a page of restaurants and a next_cursor identifying the next page.
A response looks like this:
{
"items": [
{ "id": 1, "name": "Farmhouse" }
],
"next_cursor": "eyJpZCI6MjB9"
}The final page returns an empty next_cursor.
A normal useQuery represents one result. An infinite query represents a sequence of results that you can extend as the customer scrolls.
TanStack Query v5 needs two pieces of pagination information:
initialPageParamtells it what to use for the first request.getNextPageParamtells it how to obtain the next page parameter from the current page.
For this API, the first page uses an empty cursor. The pagination helper converts the empty next_cursor into undefined.
export function nextCursor(
page: Page<unknown>,
): string | undefined {
return page.next_cursor || undefined;
}The important detail is the return value. undefined means that there is no next page. It causes hasNextPage to become false.
Returning an empty string instead can leave the query with a valid-looking page parameter and cause another request for the first page.
Page parameters and query data
The query stores the results in data.pages. Each entry represents one response from the API.
The application can keep those page boundaries while displaying one continuous list.
export function flatten<T>(
pages: Page<T>[] | undefined,
): T[] {
return pages?.flatMap(page => page.items) ?? [];
}This transformation preserves the order of the pages and the items inside them.
The API client handles the actual request. The restaurant fetching function constructs the URL using restaurantsPath and passes it to the API client, rather than calling fetch directly.
The query function receives the page parameter from TanStack Query. It does not need to manage the cursor itself.
For the restaurant list, the query uses:
initialPageParam: "",
getNextPageParam: nextCursor,
staleTime: 60_000,The first request has no cursor parameter in its URL. Subsequent requests use the cursor returned by the previous page.
fetchNextPage() requests another page. hasNextPage tells the screen whether another page exists, and isFetchingNextPage indicates whether that request is already running.
The screen should guard fetchNextPage() with both flags. Otherwise, repeated end-of-list events can start unnecessary requests.


Cache freshness and retention
Two settings control how long cached data remains useful.
staleTime
staleTime defines how long data is considered fresh.
The restaurant list uses 60 seconds:
staleTime: 60_000During that period, reopening the screen can use cached data without another request. Once the data becomes stale, TanStack Query can refetch it when a component mounts or when a configured focus or reconnect event occurs.
The menu uses five minutes because customers may navigate from the restaurant list to the menu and then into the configurator. Reusing the same menu query during that interval avoids another request.
An important distinction: staleTime does not schedule a request for exactly the moment the timer expires. It determines freshness. A later event, such as mounting or reconnecting, can trigger the refetch.
gcTime
gcTime controls how long an inactive query remains in the cache after its last observer unmounts.
The default is five minutes.
Consider a customer who opens a restaurant menu and then navigates back to the restaurant list. The menu screen unmounts, but its query can remain in the cache.
When the customer opens that restaurant again within the retention period, TanStack Query can reuse the cached result.
The difference is:
| Setting | Controls |
|---|---|
staleTime | How long data remains fresh |
gcTime | How long inactive data remains in the cache |
A query can be stale but still cached. Stale data can be displayed while a background refetch runs.
Query retry policy
A network request can fail for different reasons.
A temporary connection failure might succeed on another attempt. A 404 will not become successful by repeating the same request.
TanStack Query retries failed queries by default. The app overrides that behaviour at the shared query-client level.
retry: (failures, err) =>
!(err instanceof ApiError && err.status < 500) &&
failures < 2,This policy means:
- Network failures can be retried, up to two retries.
5xxresponses can be retried, up to two retries.4xxresponses are never retried.
The distinction matters for the menu screen. A missing restaurant produces a 404. Repeating that request does not help, so the screen should receive the error without waiting for additional retries.
A 401 normally does not reach this retry policy while authentication is working. The API client performs silent refresh when appropriate. If silent refresh fails, the resulting authentication error should not be retried as an ordinary query failure.
React Native focus and network events
On the web, TanStack Query can listen to browser lifecycle and network events. React Native does not provide the same browser APIs.
A phone can switch between active and background states without destroying the app. It can also lose its network connection while a screen remains mounted.
You need to connect these events to TanStack Query once, when the shared query client is created.
Application focus
The focusManager tells TanStack Query whether the app is currently active.
React Native exposes application state through AppState. When the state becomes "active", the app has returned to the foreground.
AppState.addEventListener("change", status => {
if (Platform.OS !== "web") {
focusManager.setFocused(status === "active");
}
});When the app becomes active, stale queries can refetch.
This is different from screen focus. A phone can remain active while the customer navigates from the restaurant list to a menu. The app has not gone into the background, but the restaurant screen is no longer the active route.
Network connectivity
The onlineManager tells TanStack Query whether the device has network connectivity.
In this app, expo-network provides network-state events.
onlineManager.setEventListener(setOnline => {
const subscription = Network.addNetworkStateListener(
state => setOnline(state.isConnected !== false),
);
return () => subscription.remove();
});When the device loses its connection, queries can pause instead of repeatedly failing. When connectivity returns, paused queries can resume.
This is particularly useful for the restaurant list. A customer can enter an area with poor connectivity, continue seeing cached restaurants and get updated data after reconnecting.
These two integrations are the focus and online wiring:
AppStateupdates application focus.expo-networkupdates network connectivity.
The shared query client belongs at module level in lib/queryClient.ts. The root layout imports that instance and provides it through QueryClientProvider.
Do not create a separate query client inside every screen. Separate instances would have separate caches and defeat the purpose of sharing server state.
Screen-scoped polling
Some server data changes while the customer is looking at it. Before Week 5 adds WebSockets, the order detail screen uses polling to request the latest order status on a timer.
For example, the app can check an in-progress order every 10 seconds.
There is a phone-specific issue with this approach. Expo Router can keep a previous screen mounted underneath a newly pushed screen.
Imagine this sequence:
- The customer opens an order detail screen.
- The order screen starts polling.
- The customer navigates to another screen.
- The order screen remains mounted underneath it.
If polling depends only on whether the component is mounted, requests continue while the customer is looking somewhere else.
Use route focus to control the polling interval.
const focused = useIsFocused();
return useQuery({
queryKey: ["orders", id],
queryFn: () => fetchOrder(api, id),
refetchInterval: query =>
focused ? pollInterval(query.state.data) : false,
});useIsFocused from Expo Router tells you whether the route is currently on top.
The interval also depends on the order status. The app polls every 10 seconds while the order is moving. Once it reaches a final status such as delivered, cancelled or rejected, pollInterval returns false.
This gives you two separate conditions:
- The app must be showing the order screen.
- The order must still be in a state that can change.
Week 5 replaces this polling approach with WebSockets. The server pushes order status and rider location updates instead of waiting for the next scheduled request.
Mutations and cache invalidation
Queries read server state. Mutations change it.
When a customer places an order, the app uses useMutation to send the write request. A successful response contains the order created by the server.
The cached orders list is now outdated because it does not contain the new order.
Query invalidation tells TanStack Query that cached data is no longer fresh.
const order = useMutation({
mutationFn: () => placeOrder(api),
onSuccess: placed => {
void queryClient.invalidateQueries({
queryKey: ["orders"],
});
router.push({
pathname: "/orders/[id]",
params: { id: String(placed.id) },
});
},
});Invalidating the ["orders"] prefix marks matching queries stale. Queries currently in use can refetch, while inactive ones remain marked stale until needed.
This is generally preferable to manually editing the orders cache with setQueryData. The server determines order totals, statuses and ordering. Fetching the updated result keeps the client aligned with that source of truth.
A mutation's pending and error states also help the screen provide feedback. The customer can see whether the order request is still running and whether it failed.
Cache isolation on sign-out
The query cache can outlive individual screens. That is useful while a customer navigates, but it introduces an account-isolation requirement.
Suppose one customer signs out and another customer signs in on the same phone. The new customer must not see the previous customer's cached orders.
When authentication state changes to signed out, the root navigator clears the query client:
useEffect(() => {
if (!isLoading && !isSignedIn) {
queryClient.clear();
}
}, [isLoading, isSignedIn]);This removes the previous account's cached queries.
The cache is shared across screens, but it should not be shared across unrelated authenticated sessions.
Restaurant and menu screens
The restaurant list combines several of these ideas. Its query identifies the delivery area through its query key, stores cursor-based pages and uses lifecycle events to refresh stale data.
The menu screen uses a normal query instead of an infinite query. Its key includes the restaurant id, and its five-minute freshness period allows the configurator to reuse the same menu data.
Both screens should distinguish an initial loading failure from a background refresh failure. Cached data remains useful while another request is running or has failed.
Keep these responsibilities separate: the API client makes requests, TanStack Query manages server state, and React Native components render the available data.
Check your understanding
The restaurant request depends on latitude 28.46, longitude 77.03 and radius 5. What happens if the query key contains only ["restaurants"] and the customer changes their delivery location?
References
Everything above is explained on this page; these are where it comes from (TanStack Query v5, expo-network (Expo SDK 58)).