Skip to main content

Lesson 2 of 9

TanStack Query - Caching & Background Sync

TanStack Query (React Query) is the gold standard for server state in React Native. It handles loading, error, and stale data states automatically, caches results across screens, and refreshes in the background when the app is foregrounded.

35 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Installation & Setup

Installation & Setup
npm install @tanstack/react-query

// App.tsx
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { AppState } from 'react-native';
import type { AppStateStatus } from 'react-native';
import { focusManager } from '@tanstack/react-query';

// ---- Mobile focus manager: refetch on app foreground ----
function onAppStateChange(status: AppStateStatus) {
  focusManager.setFocused(status === 'active');
}

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 30_000,      // data fresh for 30s before background refetch
      gcTime: 5 * 60_000,     // keep in cache for 5 minutes after unmount
      retry: 2,               // retry failed requests twice
      refetchOnWindowFocus: false, // handled by AppState above
    },
  },
});

export default function App() {
  useEffect(() => {
    const sub = AppState.addEventListener('change', onAppStateChange);
    return () => sub.remove();
  }, []);

  return (
    <QueryClientProvider client={queryClient}>
      <App />
    </QueryClientProvider>
  );
}

Queries & Mutations

Queries & Mutations
import { useQuery, useMutation, useQueryClient, useInfiniteQuery } from '@tanstack/react-query';

// ---- Query keys - typed factory ----
export const postKeys = {
  all: ['posts'] as const,
  lists: () => [...postKeys.all, 'list'] as const,
  list: (page: number) => [...postKeys.lists(), { page }] as const,
  details: () => [...postKeys.all, 'detail'] as const,
  detail: (id: string) => [...postKeys.details(), id] as const,
};

// ---- useQuery: fetch a single post ----
function PostDetail({ postId }: { postId: string }) {
  const { data: post, isLoading, isError, error, refetch } = useQuery({
    queryKey: postKeys.detail(postId),
    queryFn: () => postService.getPost(postId),
    staleTime: 60_000,  // this specific query fresh for 1 minute
  });

  if (isLoading) return <ActivityIndicator />;
  if (isError) return (
    <View>
      <Text style={{ color: '#f87171' }}>{(error as Error).message}</Text>
      <Pressable onPress={() => refetch()}><Text>Retry</Text></Pressable>
    </View>
  );
  return <Text style={{ color: '#f1f5f9' }}>{post?.title}</Text>;
}

// ---- useInfiniteQuery: paginated feed ----
function PostFeed() {
  const {
    data,
    isLoading,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
    refetch,
    isRefetching,
  } = useInfiniteQuery({
    queryKey: postKeys.lists(),
    queryFn: ({ pageParam = 1 }) => postService.getPosts(pageParam),
    getNextPageParam: (lastPage) => lastPage.hasNextPage ? lastPage.page + 1 : undefined,
    initialPageParam: 1,
  });

  const posts = data?.pages.flatMap(p => p.data) ?? [];

  return (
    <FlatList
      data={posts}
      keyExtractor={p => p.id}
      renderItem={({ item }) => <PostCard post={item} />}
      onEndReached={() => { if (hasNextPage && !isFetchingNextPage) fetchNextPage(); }}
      onEndReachedThreshold={0.3}
      ListFooterComponent={isFetchingNextPage ? <ActivityIndicator /> : null}
      refreshing={isRefetching}
      onRefresh={refetch}
    />
  );
}

// ---- useMutation: create post with optimistic update ----
function CreatePostForm() {
  const queryClient = useQueryClient();

  const mutation = useMutation({
    mutationFn: (dto: CreatePostDto) => postService.createPost(dto),

    // Optimistic update - show new post immediately
    onMutate: async (newDto) => {
      await queryClient.cancelQueries({ queryKey: postKeys.lists() });
      const previous = queryClient.getQueryData(postKeys.lists());

      queryClient.setQueryData(postKeys.lists(), (old: unknown) => {
        const pages = (old as { pages: { data: Post[] }[] })?.pages ?? [];
        const optimisticPost: Post = { id: 'temp-' + Date.now(), ...newDto, userId: 'me' };
        return { ...old, pages: [{ ...pages[0], data: [optimisticPost, ...pages[0].data] }, ...pages.slice(1)] };
      });

      return { previous };
    },

    onError: (_, __, context) => {
      // Roll back on error
      queryClient.setQueryData(postKeys.lists(), context?.previous);
    },

    onSettled: () => {
      // Always refetch to sync with server
      queryClient.invalidateQueries({ queryKey: postKeys.lists() });
    },
  });

  return (
    <Pressable
      onPress={() => mutation.mutate({ title: 'New Post', body: 'Content here' })}
      disabled={mutation.isPending}
    >
      <Text>{mutation.isPending ? 'Posting...' : 'Create Post'}</Text>
    </Pressable>
  );
}

interface CreatePostDto { title: string; body: string; }
interface Post { id: string; title: string; body: string; userId: string; }
function PostCard({ post }: { post: Post }) { return null; }

Tip

Tip

Practice TanStack Query Caching Background Sync in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagramโ€ฆ

Server state management, caching intervals, and AppState focus refetching

Practice Task

Note

Practice Task - (1) Write a working example of TanStack Query Caching Background Sync from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with TanStack Query Caching Background Sync is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react native code.

Topics in This Module

0/9 done