What is TanStack Query (React Query) and what does it solve?

EasyEcosystemTheory Question

Hint

Async state manager for server data — caching, background refetch, stale-while-revalidate, mutations

Full Answer

React Query manages server state with automatic caching, background updates, and synchronization — things you'd have to build manually with useEffect.

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

// ─── Query — fetch and cache ──────────────────────────────────────────────────
function UserProfile({ id }) {
  const { data: user, isLoading, error } = useQuery({
    queryKey: ['user', id],      // cache key — same key = same cache
    queryFn: () => api.getUser(id),
    staleTime: 5 * 60 * 1000,   // treat as fresh for 5 minutes
    gcTime: 10 * 60 * 1000,     // keep in cache for 10 minutes
  });

  if (isLoading) return <Skeleton />;
  if (error) return <Error />;
  return <p>{user.name}</p>;
}

// ─── Mutation — update and invalidate ────────────────────────────────────────
function UpdateUser() {
  const queryClient = useQueryClient();
  const mutation = useMutation({
    mutationFn: (data) => api.updateUser(data),
    onSuccess: (data) => {
      // Invalidate cache → triggers refetch of all user queries
      queryClient.invalidateQueries({ queryKey: ['user'] });
      // OR optimistic update
      queryClient.setQueryData(['user', data.id], data);
    },
  });

  return (
    <button
      onClick={() => mutation.mutate({ id: 1, name: 'Bob' })}
      disabled={mutation.isPending}
    >
      {mutation.isPending ? 'Saving...' : 'Save'}
    </button>
  );
}
💡 React Query replaces much of what people used Redux for — loading states, error states, cached server data, and refetch logic. Use Redux or Zustand only for genuine UI state (modals, sidebars, form wizards).

More Ecosystem Questions

Practice this in a timed sprint

5 free questions, no signup required