TanStack Query's useSuspenseQuery
You'll learn how to enable Suspense mode in TanStack Query so cache misses automatically trigger Suspense boundaries instead of requiring manual loading states.
The Traditional Query Problem
With regular useQuery, you manually check isLoading and isError to show different UI states. This forces you to handle loading logic inside every component that fetches data, creating the imperative loading problem we've discussed.
What useSuspenseQuery Does
useSuspenseQuery is TanStack Query's Suspense-aware hook. When data isn't in the cache (a cache miss), it throws a promise that the nearest Suspense boundary catches. This integrates TanStack Query's caching layer with React's declarative Suspense system.
Think of it like this: regular useQuery is like a component that says "I'll tell you when I'm loading." Meanwhile, useSuspenseQuery says "I'll just pause here—you (Suspense boundary) handle the loading UI."
The Integration
import { useSuspenseQuery } from '@tanstack/react-query';
function UserProfile({ userId }) {
// No isLoading check needed!
const { data } = useSuspenseQuery({
queryKey: ['user', userId],
queryFn: () => fetchUser(userId)
});
return <div>{data.name}</div>; // data is always defined
}
// Wrap with Suspense boundary
<Suspense fallback={<Spinner />}>
<UserProfile userId={123} />
</Suspense>
When the query's cache is empty, the hook throws the fetch promise. The Suspense boundary catches it and shows the fallback. When data arrives, React re-renders with the data available.
Key Takeaway: useSuspenseQuery bridges TanStack Query's cache management with Suspense boundaries, eliminating manual loading states by suspending components during cache misses.