Capítulo 77 de 80

Chapter 77: usePrefetchQuery

Core Idea

The Suspense-safe way to prefetch — call during render, before a <Suspense> boundary wraps the component that actually calls useSuspenseQuery for that same data, so the fetch starts without itself suspending.

Key Concepts

  • Options: everything queryClient.query() accepts; queryKey required, queryFn required unless a default is registered.
  • Returns nothing: this hook's only job is triggering the prefetch as a side effect of rendering — it never gives you the data directly.
  • Placement matters: must be called in a component outside/above the <Suspense> boundary that wraps the actual useSuspenseQuery consumer — calling it inside the boundary (or using useSuspenseQuery itself to "prefetch") defeats the purpose.

Code Examples

function ArticleLayout({ id }) {
  usePrefetchQuery({ queryKey: ['article-comments', id], queryFn: getArticleCommentsById })
  return <Suspense fallback="Loading article"><Article id={id} /></Suspense>
}
  • What it demonstrates: starting a fetch before the boundary that will eventually suspend on a different, "primary" query.

Key Takeaways

  1. Never use useSuspenseQuery itself to prefetch — it would suspend the calling component, defeating the point. This hook is the dedicated, non-suspending alternative.

Connects To

  • Prefetching & Router Integration: the full conceptual guide for this hook's placement.
  • Suspense: the boundary/fallback model this hook is designed around.