Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 38 ยท Data, Storage and Networking

Caching Server Data with TanStack Query

Fetch, cache and refresh server data in Expo with TanStack Query: useQuery, query keys, staleTime, mutations with optimistic updates, focus refetch and persisted offline cache.

Calling fetch inside useEffect works for one screen. Then the app grows. Two screens need the same user, so you fetch it twice. You go back to a list and it reloads from scratch. A request fails and you retry by hand. Each screen re-implements loading and error flags.

TanStack Query (formerly React Query) solves this by treating server data as a cache that your components subscribe to. It works in Expo exactly as it does on the web, with a few mobile hooks to wire up focus and connectivity.

What runs on this site. The library is not available in the in-browser runner, so the real code is read-only. The runnable examples are a tiny hand-written query cache that shows the same ideas: keys, stale time, request sharing and invalidation.

Setup

Terminal
npx expo install @tanstack/react-query
JSX
// app/_layout.jsx
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { Stack } from 'expo-router';

const queryClient = new QueryClient({
  defaultOptions: { queries: { staleTime: 60_000, retry: 2 } },
});

export default function RootLayout() {
  return (
    <QueryClientProvider client={queryClient}>
      <Stack />
    </QueryClientProvider>
  );
}

Reading data with useQuery

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

function Profile({ id }) {
  const { data, isPending, isError, error, refetch, isRefetching } = useQuery({
    queryKey: ['user', id],
    queryFn: () => api(`/users/${id}`),
  });

  if (isPending) return <ActivityIndicator />;
  if (isError) return <Text onPress={refetch}>Failed: {error.message}. Tap to retry.</Text>;
  return <Text>{data.name}</Text>;
}

Two things matter most:

  • The query key (['user', id]) identifies the data. Same key, same cache entry, shared by every component. A different id is a different entry.
  • The query function returns a promise. It must throw on failure, which is why the networking lesson checks response.ok.

Fresh, stale and garbage collected

Cached data has a life cycle:

flowchart LR
  A["fetching"] --> B["fresh<br/>(within staleTime)"]
  B --> C["stale<br/>(shown instantly, refetched on use)"]
  C --> D["inactive<br/>(no screen uses it)"]
  D --> E["removed after gcTime"]
  C --> A

While data is fresh it is served from the cache with no request. Once stale, it is still shown instantly and refreshed in the background.

Node.js A tiny query cache (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Changing data with useMutation

Reads are queries; writes are mutations. After a successful write, tell the cache which data is now out of date:

JSX
const queryClient = useQueryClient();

const addTodo = useMutation({
  mutationFn: (title) => api('/todos', { method: 'POST', body: JSON.stringify({ title }) }),
  onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
});

<Button title="Add" onPress={() => addTodo.mutate('Buy milk')} disabled={addTodo.isPending} />

Optimistic updates

For instant feedback, update the cache before the server answers, and undo if it fails:

JSX
useMutation({
  mutationFn: toggleTodo,
  onMutate: async (id) => {
    await queryClient.cancelQueries({ queryKey: ['todos'] });
    const previous = queryClient.getQueryData(['todos']);
    queryClient.setQueryData(['todos'], (list) =>
      list.map((t) => (t.id === id ? { ...t, done: !t.done } : t)));
    return { previous };
  },
  onError: (_err, _id, context) => queryClient.setQueryData(['todos'], context.previous),
  onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
});
Node.js Optimistic update with rollback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Mobile specifics

On the web, TanStack Query refetches when the browser tab regains focus and when the network returns. Apps need two small adapters:

JSX
import { AppState } from 'react-native';
import { focusManager, onlineManager } from '@tanstack/react-query';
import * as Network from 'expo-network';

AppState.addEventListener('change', (status) => focusManager.setFocused(status === 'active'));

onlineManager.setEventListener((setOnline) => {
  const sub = Network.addNetworkStateListener((s) => setOnline(!!s.isConnected));
  return sub.remove;
});

Also refetch when a screen is focused in navigation, using useFocusEffect from Expo Router.

Persisting the cache for offline use

@tanstack/react-query-persist-client can save the cache to AsyncStorage, so the app opens instantly with the last known data, even offline:

JSX
import { createAsyncStoragePersister } from '@tanstack/query-async-storage-persister';
import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client';
import AsyncStorage from '@react-native-async-storage/async-storage';

const persister = createAsyncStoragePersister({ storage: AsyncStorage });
// Use gcTime longer than the persist maxAge, e.g. 24 hours.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the query key identify?

    The key is the cache identity. Same key, same data and the same request.
  2. 2. What happens when data is stale and a component reads it?

    Stale-while-revalidate: the UI stays instant, and the data is refreshed.
  3. 3. When should you call invalidateQueries?

    Invalidation marks entries stale so they refetch with the new server state.
  4. 4. Why does an optimistic update store the previous data?

    If the server rejects the change, you roll the UI back to the snapshot.

Summary

  • TanStack Query treats server data as a shared cache keyed by queryKey.
  • staleTime decides when cached data needs a background refresh.
  • Mutations change data; invalidate or optimistically update the affected keys.
  • Connect AppState and network state so focus and reconnect refetching work on mobile.
  • Persist the cache to AsyncStorage for instant, offline-friendly startup.

Next: Push notifications basics