Skip to main content

Lesson 5 of 9

TanStack Query - Server State Mastery

TanStack Query (React Query) fundamentally changes how you handle server data in React. It provides automatic caching, background refetching, loading/error/stale states, optimistic updates, and infinite queries - completely eliminating the useState+useEffect+cleanup pattern for API calls.

35 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Setup & Core Patterns

Setup & Core Patterns
import { QueryClient, QueryClientProvider, useQuery, useMutation, useQueryClient } from '@tanstack/react-query';

// main.tsx - configure QueryClient
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 5 * 60 * 1000,       // data is fresh for 5 minutes
      gcTime: 10 * 60 * 1000,          // keep unused data in cache for 10 minutes
      retry: 3,                         // retry failed requests 3 times
      refetchOnWindowFocus: true,       // refetch when user returns to tab
    },
  },
});

<QueryClientProvider client={queryClient}>
  <ReactQueryDevtools initialIsOpen={false} />
  <App />
</QueryClientProvider>

// useQuery - fetch and cache data
function UserProfile({ userId }: { userId: string }) {
  const { data: user, isLoading, isError, error, isFetching } = useQuery({
    queryKey: ['user', userId],     // cache key - unique per userId
    queryFn: () => fetchUser(userId),
    enabled: !!userId,              // only run if userId is truthy
    staleTime: 60_000,              // override global: fresh for 1 min
    select: (data) => ({            // transform data before returning
      ...data,
      displayName: `${data.firstName} ${data.lastName}`,
    }),
  });

  if (isLoading) return <Skeleton />;
  if (isError) return <ErrorMessage error={error} />;

  return (
    <div>
      {isFetching && <RefreshIndicator />} {/* background refetch indicator */}
      <h1>{user?.displayName}</h1>
    </div>
  );
}

// Query key strategy - hierarchical for easy invalidation
const keys = {
  users: ['users'] as const,
  user: (id: string) => ['users', id] as const,
  userPosts: (id: string) => ['users', id, 'posts'] as const,
};

// Invalidate all users queries at once
queryClient.invalidateQueries({ queryKey: ['users'] });

useMutation & Optimistic Updates

useMutation & Optimistic Updates
// useMutation - create, update, delete operations
function useUpdateUser() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ id, data }: { id: string; data: Partial<User> }) =>
      fetch(`/api/users/${id}`, {
        method: 'PATCH',
        body: JSON.stringify(data),
        headers: { 'Content-Type': 'application/json' },
      }).then(r => r.json()),

    // Optimistic update - immediately reflect the change before server responds
    onMutate: async ({ id, data }) => {
      await queryClient.cancelQueries({ queryKey: ['users', id] }); // prevent race
      const previousUser = queryClient.getQueryData(['users', id]);  // snapshot

      queryClient.setQueryData(['users', id], (old: User) => ({ ...old, ...data })); // optimistic

      return { previousUser }; // return snapshot for rollback
    },

    onError: (err, { id }, context) => {
      // Rollback on error
      queryClient.setQueryData(['users', id], context?.previousUser);
      toast.error('Update failed');
    },

    onSettled: (_, __, { id }) => {
      // Always refetch after mutation to ensure consistency
      queryClient.invalidateQueries({ queryKey: ['users', id] });
    },
  });
}

// Usage in component
function EditUserForm({ user }: { user: User }) {
  const updateUser = useUpdateUser();

  function handleSubmit(data: Partial<User>) {
    updateUser.mutate({ id: user.id, data }, {
      onSuccess: () => toast.success('Profile updated!'),
    });
  }

  return (
    <form onSubmit={handleSubmit}>
      {updateUser.isPending && <Spinner />}
      ...
    </form>
  );
}

Common Mistakes - TanStack Query

  • Using unstable query keys - `queryKey: ['users', new Date()]` creates a new key on every render, causing infinite fetching; keys must be stable
  • Not providing `enabled` - if a dependency (like userId) is undefined, the query runs with undefined params; use `enabled: !!userId` to gate execution
  • Duplicating server data in Zustand - after fetching with TanStack Query, don't also store the result in Zustand; that creates two sources of truth that get out of sync
  • Over-invalidating - `queryClient.invalidateQueries({})` (no key) invalidates the entire cache including data that didn't change; always provide specific query keys
  • Not using `select` for data transformation - transforming data inside the queryFn means the raw data is cached; placing transformation in `select` keeps the cache clean and the component gets the transformed data

Tip

Tip

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

Diagram
Loading diagram…

Visual architecture and flow for TanStack Query - Server State Mastery

Practice Task

Note

Practice Task - (1) Write a working example of TanStack Query Server State Mastery 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 Server State Mastery is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.

Key Takeaways

  • TanStack Query (React Query) fundamentally changes how you handle server data in React.
  • Using unstable query keys - `queryKey: ['users', new Date()]` creates a new key on every render, causing infinite fetching; keys must be stable
  • Not providing `enabled` - if a dependency (like userId) is undefined, the query runs with undefined params; use `enabled: !!userId` to gate execution
  • Duplicating server data in Zustand - after fetching with TanStack Query, don't also store the result in Zustand; that creates two sources of truth that get out of sync

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/9 done