Server State and Caching

Article · 2:00

TanStack Query, and why the loading flag you keep writing by hand is the wrong abstraction.

This lesson has 1 runnable example. Press Try yourself! under any of them to open it in the editor.

Most of what people call state management is actually a cache of somebody else's data. Server state is different from client state in every important way: you do not own it, it goes stale, two screens want the same copy, and it has to be refetched when the app returns from the background. Storing it in useState means writing isLoading, error and data by hand on every screen, and getting the edge cases wrong on most of them.

TanStack Query owns that problem. A useQuery with a key returns the data, the loading and error state, and keeps one cache entry shared by every component asking for the same key. It deduplicates concurrent requests, refetches when the app comes back to the foreground, and serves the cached value immediately while it revalidates.

For writes, useMutation plus invalidateQueries is the ordinary pattern: change it on the server, then mark the affected queries stale. Optimistic updates go one better - apply the change locally first, roll it back if the request fails - and on mobile that is worth the extra code, because the network delay is long enough to feel.

Pagination has a dedicated hook, useInfiniteQuery, which pairs with a FlatList's onEndReached to give you an endless feed in a few lines.

TS Example 1 51 lines
import { useQuery, useMutation, useQueryClient, useInfiniteQuery } from '@tanstack/react-query';
import { api } from './api';

// Read. One cache entry per key, shared by every component that asks.
export function useArticles() {
  return useQuery({
    queryKey: ['articles'],
    queryFn: () => api<Article[]>('/articles'),
    staleTime: 60_000,       // serve from cache for a minute without refetching
    retry: 2,
  });
}

// An endless feed, driven by FlatList's onEndReached.
export function useArticleFeed() {
  return useInfiniteQuery({
    queryKey: ['articles', 'feed'],
    queryFn: ({ pageParam }) => api<Page>(`/articles?cursor=${pageParam}`),
    initialPageParam: '',
    getNextPageParam: (last) => last.nextCursor ?? undefined,
  });
}

// Write, optimistically: apply it now, undo it if the server disagrees.
export function useToggleRead() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (id: string) => api(`/articles/${id}/read`, { method: 'POST' }),

    onMutate: async (id) => {
      await queryClient.cancelQueries({ queryKey: ['articles'] });
      const previous = queryClient.getQueryData<Article[]>(['articles']);

      queryClient.setQueryData<Article[]>(['articles'], (old) =>
        old?.map((a) => (a.id === id ? { ...a, isRead: true } : a)),
      );

      return { previous };    // handed to onError as context
    },

    onError: (_error, _id, context) => {
      // Put it back exactly as it was.
      queryClient.setQueryData(['articles'], context?.previous);
    },

    onSettled: () => {
      queryClient.invalidateQueries({ queryKey: ['articles'] });
    },
  });
}

Open this example in the editor and change it. Nothing you type is saved.