Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 71 ยท State and Data

Server State with TanStack Query

Fetch, cache and update server data in React Native with TanStack Query: stale time, focus and online managers, optimistic updates and offline mutations.

In Networking with fetch you wrote the loading, error and cancel logic by hand. It works, but you would write it again for every screen, and you would still be missing things users expect: showing the old data instantly while new data loads, not requesting the same list twice when two components need it, retrying when the connection returns, and updating the screen the moment a user taps "like" instead of after a round trip.

TanStack Query (formerly React Query) is a library for exactly this kind of data, called server state: information that lives on a server, that you only hold a copy of, and that can become out of date. It is different from the client state you keep in Zustand or Redux, which you own completely.

What runs on this site. TanStack Query is installed with npm in a real project, so its code here is read-only. The runnable examples are stand-ins: a mini cache with stale time and request sharing, and an optimistic-update demo with an offline queue. They teach the behaviour, but they are not the library.

Setting it up

You create one QueryClient and put it in a provider near the root of the app.

JSX
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

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

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

The library works in React Native without extra packages for the basics. For mobile behaviours (app focus and connectivity) you add a few lines, shown below.

Queries: reading data

A query is a read. You give it a key that identifies the data and a function that fetches it. Everything else (status, caching, retries) is handled for you.

JSX
import { useQuery } from '@tanstack/react-query';
import { FlatList, Text, ActivityIndicator } from 'react-native';

function NotesScreen() {
  const { data, isPending, isError, error, refetch, isRefetching } = useQuery({
    queryKey: ['notes'],
    queryFn: () => getJson(`${API_URL}/notes`),
  });

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

  return (
    <FlatList
      data={data}
      keyExtractor={(note) => String(note.id)}
      renderItem={({ item }) => <Text>{item.title}</Text>}
      refreshing={isRefetching}
      onRefresh={refetch}
    />
  );
}

Two settings explain most of its behaviour:

  • staleTime: how long data counts as fresh. While fresh, mounting the screen again does not hit the network. The default is 0, meaning data is stale immediately.
  • gcTime (garbage-collection time): how long unused data stays in memory after the last component stops using it. The default is five minutes.

When data is stale and a component mounts, TanStack Query shows the cached copy at once and refetches in the background. This pattern, "stale while revalidate", is why navigating back to a list feels instant.

One key, one cache entry

Query key Names the data, like ['notes'] or ['note', 7].
Cache Holds the latest result for each key.
Sharing Two screens with the same key share one request.
1 / 2

Explore it with a mini cache. The clock is virtual, so you control time with a button. Open a screen, close it, open it again, then advance the clock past the stale time and open it once more.

A mini query cache with stale time

Try opening A and B together on a fresh page: the second one joins the request already in flight, so only one request is made.

Mutations: changing data

A mutation is a write: create, update or delete. useMutation gives you a mutate function and a isPending flag. After a write succeeds, the cached lists are out of date, so you invalidate them and the library refetches:

JSX
import { useMutation, useQueryClient } from '@tanstack/react-query';

function AddNote() {
  const queryClient = useQueryClient();
  const mutation = useMutation({
    mutationFn: (title) =>
      fetch(`${API_URL}/notes`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ title }),
      }).then((r) => {
        if (!r.ok) throw new Error('Could not save');
        return r.json();
      }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['notes'] }),
  });

  return (
    <Pressable disabled={mutation.isPending} onPress={() => mutation.mutate('Buy milk')}>
      <Text>{mutation.isPending ? 'Saving...' : 'Add note'}</Text>
    </Pressable>
  );
}

Mobile: focus and online managers

On the web, TanStack Query refetches stale data when the browser tab regains focus, and pauses requests when the browser is offline. A phone has neither a tab nor window events, so the library needs to be told. Two small managers do this:

JSX
import { useEffect } from 'react';
import { AppState, Platform } from 'react-native';
import { focusManager, onlineManager } from '@tanstack/react-query';
import NetInfo from '@react-native-community/netinfo';

// 1. Online status from the device's connectivity
onlineManager.setEventListener((setOnline) =>
  NetInfo.addEventListener((state) => setOnline(!!state.isConnected)),
);

// 2. "Focus" means the app is in the foreground
export function useAppFocus() {
  useEffect(() => {
    const subscription = AppState.addEventListener('change', (status) => {
      if (Platform.OS !== 'web') focusManager.setFocused(status === 'active');
    });
    return () => subscription.remove();
  }, []);
}

With these two in place, returning to the app after a coffee break refetches stale queries, and losing the connection pauses requests until it is back. A third mobile habit is refetching when a screen becomes visible again, because tab and stack screens stay mounted. React Navigation's useFocusEffect does that:

JSX
import { useFocusEffect } from '@react-navigation/native';
import { useCallback } from 'react';

useFocusEffect(
  useCallback(() => {
    refetch();
  }, [refetch]),
);

(Call refetch only when the data is stale if you want to avoid double requests on the first mount.)

Optimistic updates

For a "like" button or a checkbox, waiting for the server makes the app feel sluggish. An optimistic update changes the screen immediately and quietly undoes the change if the server says no. In TanStack Query you use the lifecycle callbacks of useMutation:

JSX
const toggleDone = useMutation({
  mutationFn: (id) => api.toggleTodo(id),
  onMutate: async (id) => {
    await queryClient.cancelQueries({ queryKey: ['todos'] }); // stop in-flight refetches overwriting us
    const previous = queryClient.getQueryData(['todos']);      // remember for rollback
    queryClient.setQueryData(['todos'], (todos) =>
      todos.map((t) => (t.id === id ? { ...t, done: !t.done } : t)),
    );
    return { previous };
  },
  onError: (error, id, context) => {
    queryClient.setQueryData(['todos'], context.previous);     // roll back
  },
  onSettled: () => {
    queryClient.invalidateQueries({ queryKey: ['todos'] });    // re-sync with the truth
  },
});

The four steps are always the same: cancel, snapshot, apply, and then either roll back on error or re-sync when settled.

Offline mutations

By default a mutation made while the device is offline pauses (isPaused becomes true) and runs when the connection returns, in the order it was made. To survive an app restart, you persist the cache with PersistQueryClientProvider and an AsyncStorage persister, give mutations default functions by key so they can be resumed, and call resumePausedMutations after the cache is restored:

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

const queryClient = new QueryClient({
  defaultOptions: { queries: { gcTime: 1000 * 60 * 60 * 24 } }, // keep at least as long as maxAge
});
queryClient.setMutationDefaults(['toggleTodo'], { mutationFn: (id) => api.toggleTodo(id) });

const persister = createAsyncStoragePersister({ storage: AsyncStorage });

<PersistQueryClientProvider
  client={queryClient}
  persistOptions={{ persister }}
  onSuccess={() => queryClient.resumePausedMutations()}
>
  <Navigation />
</PersistQueryClientProvider>

Offline-first writes bring a design question you must answer: what if two devices edit the same record? The library resends your changes, but deciding who wins is your server's job.

The next stand-in combines an optimistic update, a rollback and a paused queue. Toggle a todo while online. Then go offline, toggle several, and go online again to watch them flush in order. Tick the checkbox to make the server reject the next toggle and see the rollback.

Optimistic updates, rollback and an offline queue

When to reach for it

Use TanStack Query for anything that comes from an API and can change. Keep the cart, the theme and form drafts in a client store. A rule of thumb: if you find yourself writing isLoading state and a useEffect that fetches, a query is almost always cleaner.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens when a screen mounts and its query data is stale?

    This is stale-while-revalidate: users see something immediately, and the screen updates when fresh data arrives.
  2. 2. Why does a React Native app set up focusManager and onlineManager?

    On the web the library listens to window focus and the online event. In React Native you connect AppState and NetInfo to the managers yourself.
  3. 3. Which is the correct order of an optimistic update?

    Cancelling stops an in-flight refetch from overwriting the optimistic value, the snapshot allows rollback, and onSettled re-syncs with the server.
  4. 4. Which data fits TanStack Query best?

    Server state, such as an API list that can go stale and needs caching and refetching, is what the library is built for. UI state belongs in useState or a client store.

Summary

  • TanStack Query manages server state: caching, sharing requests by key, background refetching and retries.
  • useQuery reads (key plus function); staleTime controls freshness and gcTime controls memory; stale data is shown instantly and refreshed.
  • useMutation writes; invalidate affected queries afterwards.
  • On mobile, connect focusManager to AppState and onlineManager to NetInfo, and refetch on screen focus if you need it.
  • Optimistic updates: cancel, snapshot, apply, roll back on error, invalidate when settled.
  • Offline mutations pause and resume; persist the cache and call resumePausedMutations to survive restarts.
  • On this site the library is read-only; the cache and queue demos are stand-ins.

Next, learn how to keep data on the device in Storing Data: AsyncStorage, MMKV and SecureStore.