Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 38 ยท Suspense and Prefetching

Router Loaders and Waterfalls

Start queries when navigation starts, not when components render: route loaders with ensureQueryData, parallel and dependent fetching, and how to spot and remove waterfalls.

Data fetching inside components has one hidden cost: a component can only ask for data after it renders, and it only renders after its parent's code, its lazy-loaded JavaScript and its parent's data are ready. A chain of such steps is a waterfall, and each link adds a full network round trip.

The cure is to start requests as early as possible: when navigation begins, using the router's loader hook, instead of when components finally render. Routers such as TanStack Router, React Router and Next.js all offer loaders. This lesson shows the pattern with TanStack Query as the cache.

Seeing a waterfall

Take a page that shows a project and its tasks. The tasks request only needs the project id from the URL, but the code below waits for the project to load before even rendering the child:

JSX
function ProjectPage({ id }) {
  const { data: project } = useSuspenseQuery(projectOptions(id)); // 1. fetch project (500 ms)
  return <Tasks projectId={project.id} />;                         // 2. child starts fetching only now
}

Total time: 500 ms + 500 ms. Since id was already known, the second request could have started at the same time as the first.

Three ways to flatten it

  1. Parallel queries. Fetch both in the same component with useSuspenseQueries or two useQuery calls that do not depend on each other.
  2. Pass the id, not the object. Use id from the route, not project.id, so Tasks does not have to wait for project.
  3. Loaders. Start both requests from the route loader before any component renders.
JS Waterfall versus parallel

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The sequential version takes about 900 ms and the parallel one about 300 ms. A real route with five requests makes the difference very visible.

The loader pattern

A loader runs when navigation starts. Instead of returning data, it fills the query cache, and the components then read it with the usual hooks. In TanStack Router this looks like the following (read-only; it needs the router package):

JSX
// routes/projects.$id.jsx
export const Route = createFileRoute("/projects/$id")({
  loader: ({ context: { queryClient }, params: { id } }) => {
    // start both, wait for both
    return Promise.all([
      queryClient.ensureQueryData(projectOptions(id)),
      queryClient.ensureQueryData(tasksOptions(id)),
    ]);
  },
  component: ProjectPage,
});

function ProjectPage() {
  const { id } = Route.useParams();
  const { data: project } = useSuspenseQuery(projectOptions(id));
  const { data: tasks } = useSuspenseQuery(tasksOptions(id));
  /* ... */
}

React Router v7 data routers use the same idea with loader functions receiving params, and Next.js uses server-side prefetchQuery (previous lesson). Why ensureQueryData and not fetchQuery?

  • Returning cached data makes back navigation instant (the loader finishes at once if the cache has the data).
  • With a staleTime the cached data is considered fresh, so no refetch happens. When data is stale, the component's useSuspenseQuery triggers the background refresh after the page appears, so navigation is never blocked by a stale entry.

If you do want to block on stale data, pass revalidateIfStale: true.

Awaiting or not awaiting

You decide per query whether navigation should wait:

  • Critical data (page title, the main content): await it in the loader, so the page renders with it.
  • Secondary data (comments, related items): call queryClient.prefetchQuery(...) without awaiting (and with no return). The request starts early, the page renders immediately, and the component shows its own Suspense fallback until the data arrives.
JSX
loader: async ({ context: { queryClient }, params: { id } }) => {
  queryClient.prefetchQuery(commentsOptions(id));          // fire and forget
  await queryClient.ensureQueryData(projectOptions(id));   // wait for the important one
}

A loader stand-in you can run

A router is not available in the live editors, so here is a tiny hash router written by hand. Its "loader" fills the cache before the page component renders, and a counter shows how many requests happen.

A hand-written loader

Open project 1: one 0.7 s wait for both requests together (the counter goes to 2), and the Suspense fallback never shows because the data is already cached when the page renders. Open project 2, then project 1 again: the second visit is immediate and sends no requests, thanks to the staleTime.

How to find waterfalls in your app

  • Open the browser's network panel and look at the start times: a staircase of requests that begin one after another is a waterfall.
  • Search for components that fetch and then render children that fetch. These parent-then-child pairs are the typical source.
  • Check lazy-loaded routes: the JavaScript download also waterfalls in front of the data request unless the loader starts the data fetch in parallel with the code download.
  • Use the React Query devtools (next chapter) to see queries start.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is a request waterfall?

    In a waterfall the later request only starts after an earlier one, because the code that triggers it runs later.
  2. 2. Why use ensureQueryData in a loader instead of fetchQuery?

    ensureQueryData reuses the cache; fetchQuery refetches when data is stale.
  3. 3. How do you start a secondary request in a loader without delaying navigation?

    An unawaited prefetch starts early and fills the cache; the component's Suspense boundary handles any remaining wait.
  4. 4. Which change removes the waterfall in project.id -> Tasks?

    The child does not need the fetched object, only the id, which is known up front.

Summary

  • Components fetch late; loaders start requests when navigation begins.
  • Fill the cache in loaders with ensureQueryData (awaited) and prefetchQuery (not awaited).
  • Use route params instead of fetched objects wherever possible, and use useSuspenseQueries for parallel reads.
  • Shared queryOptions and a staleTime make repeat visits instant.
  • Look for staircases in the network panel to find waterfalls.

Next: DevTools