Hint
Async state manager for server data — caching, background refetch, stale-while-revalidate, mutations
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 ;
if (error) return ;
return {user.name}
;
}
// ─── 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 (
);
}