Skip to content

No. 49React8 min read2,187 words

Data fetching in React Server Components: patterns that work

Data fetching in React Server Components without waterfalls: parallel queries, Suspense streaming, React cache, passing promises to clients, and Server Actions.

Written by
Lazy Devs
Published
Updated
Sources
Cited inline

Key takeaways ยท 05

The short version

  1. 01In React Server Components, fetch data in the async component that renders it. You can query the database directly, with no API route in between, and the query never reaches the browser.
  2. 02Start independent requests together and await them with Promise.all. Sequential awaits across nested components create waterfalls where each query waits for the previous one.
  3. 03Put slow, non-essential data in its own component behind a Suspense boundary so the rest of the page streams immediately.
  4. 04Wrap shared reads, such as the current user, in React cache() so a layout, page and sidebar trigger one query per request. It does not cache across requests.
  5. 05Keep a client data library like TanStack Query for polling, infinite scroll and heavy client-side interaction. For initial page data, Server Components are simpler and ship less JavaScript.
On this page ยท 12

In React Server Components, data fetching moves into the component that renders the data. The component is async, it awaits a database query or fetch directly on the server, and the browser receives the rendered result, not the query. The patterns that make this work in production are short: run independent requests in parallel, put slow sections behind Suspense, deduplicate shared reads with React cache, and keep Client Components at the leaves with plain data as props.

Most of the confusion comes from carrying old habits across the server-client line. You no longer need a client cache library to render a list, or a spinner for every async boundary. You do need to think about waterfalls, deduplication and where each await happens. Here is how we structure data fetching in React and Next.js App Router projects.

Fetch in the component that needs the data

The biggest mental shift: a Server Component can be async and fetch its own data. You do not lift state or pass a userId down four levels so a leaf can call an API. The component that renders the data is the component that fetches it.

// app/projects/[id]/page.tsx
import { notFound } from "next/navigation";
import { getProject } from "@/lib/dal/projects";
 
export default async function ProjectPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const project = await getProject(id);
  if (!project) notFound();
 
  return (
    <main>
      <h1>{project.name}</h1>
      <ProjectStats projectId={project.id} />
    </main>
  );
}

Two things to notice. First, the page calls a data function directly. There is no fetch to your own API route, no extra network hop, and no JSON endpoint to secure. Second, ProjectStats fetches its own data too, which is where the main trap starts.

Put data access in one server-only layer

Calling the database from anywhere is convenient and dangerous. We keep all reads in a data access layer: server-only modules that check the session, scope the query to the user or tenant, and return only the fields the UI needs.

// lib/dal/projects.ts
import "server-only";
import { requireUser } from "@/lib/session";
import { db } from "@/lib/db";
 
export async function getProject(id: string) {
  const user = await requireUser();
  return db.project.findFirst({
    where: { id, ownerId: user.id },
    select: { id: true, name: true, createdAt: true },
  });
}

The Next.js data security guide recommends exactly this, and our guide to Next.js authentication patterns explains why checks belong here rather than in the page.

Avoid the accidental waterfall

Nested awaits run in sequence. If the page awaits the project, then ProjectStats awaits stats, then a child awaits activity, you have built a waterfall: each request waits for the one above it before it even starts. The Next.js data fetching docs cover sequential and parallel patterns side by side.

When two pieces of data do not depend on each other, start both before you await either:

export default async function ProjectPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
 
  const [project, activity] = await Promise.all([
    getProject(id),
    getRecentActivity(id),
  ]);
 
  if (!project) notFound();
  return <ProjectView project={project} activity={activity} />;
}

The rule: independent fetches go in a Promise.all. Dependent fetches (you need the project before you can query its owner) stay sequential because they have to, though you can often collapse them into one query with a join. Do not force dependent work into parallel just to look fast; you will query with missing inputs.

SituationPattern
Two independent queries on one pagePromise.all in the page
Child needs data the parent does notFetch in the child, behind Suspense if slow
Query B needs the result of query ASequential, or one query with a join
Same data needed by several componentsReact cache around the data function
Data the browser must keep fresh (polling, live updates)Client data library or a real-time channel

Start early, await late

A useful variation is to start a request in the parent and pass the promise down without awaiting it. The work begins immediately, and only the component that needs the value waits for it.

export default async function Page() {
  const statsPromise = getStats(); // starts now, not awaited
  const project = await getProjectSummary();
  return (
    <>
      <Header project={project} />
      <Suspense fallback={<StatsSkeleton />}>
        <Stats statsPromise={statsPromise} />
      </Suspense>
    </>
  );
}

Let Suspense break the blocking

Sometimes one query is slow and the rest of the page is ready. Move the slow fetch into its own component and wrap it in Suspense. The fast content renders straight away and the slow part streams in when it resolves.

import { Suspense } from "react";
 
export default async function ProjectPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const project = await getProject(id);
  if (!project) notFound();
 
  return (
    <main>
      <h1>{project.name}</h1>
      <Suspense fallback={<StatsSkeleton />}>
        <ProjectStats projectId={project.id} />
      </Suspense>
    </main>
  );
}
 
async function ProjectStats({ projectId }: { projectId: string }) {
  const stats = await computeStats(projectId); // slow, but no longer blocks the header
  return <StatsPanel stats={stats} />;
}

The project must exist before the shell renders, so that wait is intentional. The expensive stats query is decoupled by the boundary. This is the pattern we reach for most often: cheap, essential data inline; expensive, secondary data behind Suspense.

Two cautions. Size each fallback like the content it replaces, or the page will shift as it streams in. And do not wrap every component: too many boundaries make the page pop in piece by piece. With Cache Components enabled in Next.js 16, uncached data must be inside a Suspense boundary or cached, and the build tells you where you missed one. Our mental model for App Router rendering covers how the static shell and streamed parts fit together.

Deduplicate shared reads with React cache

A real app reads the current user in the layout, the page and a nav component. You do not want three identical queries per request. React's cache memoizes a function for the duration of one server request:

// lib/session.ts
import "server-only";
import { cache } from "react";
import { cookies } from "next/headers";
import { findUserBySessionToken } from "@/lib/db/sessions";
 
export const getCurrentUser = cache(async () => {
  const token = (await cookies()).get("session")?.value;
  if (!token) return null;
  return findUserBySessionToken(token); // one indexed query
});

Call getCurrentUser() anywhere during the render and only the first call queries. Identical fetch calls are deduplicated automatically, so cache is what you need for ORM calls and other non-fetch work.

This is per request only. For caching across requests and users you want Next.js caching ("use cache" with cacheLife and cacheTag, or fetch cache options), which has its own invalidation story. Do not confuse the two: per-request dedupe is always safe for user data, while a shared cache needs user or tenant IDs in its key.

Keep the client boundary thin

Server Components cannot use state or effects, so anything interactive needs a Client Component. The clean pattern: fetch on the server, pass plain data down as props, and let the Client Component own only the interaction.

// Server Component fetches; Client Component handles interaction.
export default async function CommentsSection({ postId }: { postId: string }) {
  const comments = await listComments(postId);
  return <CommentList initialComments={comments} postId={postId} />;
}

CommentList is "use client", receives the fetched comments and handles filtering or optimistic updates on top of them. Everything crossing the boundary is serialized into the page, so pass plain objects with only the fields the UI needs, not ORM model instances or whole database rows.

Passing a promise to the client

You can also pass an unresolved promise from a Server Component and read it in a Client Component with React's use hook. The server starts the work, the page streams, and the Client Component suspends until the data arrives.

"use client";
import { use } from "react";
import type { ProjectStats } from "@/lib/dal/stats";
 
export function Stats({ statsPromise }: { statsPromise: Promise<ProjectStats> }) {
  const stats = use(statsPromise);
  return <StatsChart data={stats} />;
}

This is handy when the component needs client interactivity (a chart with hover states, say) and the data is slow.

Fetching from external APIs

Not all data comes from your own database. When a Server Component calls a third-party API, a few habits keep pages fast and safe:

  • Keep secrets on the server. API keys used in Server Components never reach the browser, which is one of the quiet wins of this model. Mark the module server-only so it stays that way.
  • Set a timeout. A slow upstream API will hold your page hostage. Pass signal: AbortSignal.timeout(3000) (or whatever budget fits) to fetch, and render a fallback when it fails rather than letting the whole route hang.
  • Decide on caching explicitly. Since Next.js 15, fetch is not cached by default. For data that changes slowly, such as exchange rates or a product catalog, cache it with a lifetime and a tag so you are not calling the provider on every request.
  • Isolate the failure. Put the third-party section in its own component with its own Suspense and error boundary, so an outage in someone else's service degrades one panel instead of the page.
async function ShippingEstimate({ postcode }: { postcode: string }) {
  try {
    const res = await fetch(`${process.env.SHIPPING_API}/quote?zip=${encodeURIComponent(postcode)}`, {
      headers: { Authorization: `Bearer ${process.env.SHIPPING_KEY}` },
      signal: AbortSignal.timeout(3000),
    });
    if (!res.ok) throw new Error(`Shipping API ${res.status}`);
    const quote = await res.json();
    return <p>Estimated delivery: {quote.days} days</p>;
  } catch {
    return <p>Delivery estimate unavailable right now.</p>;
  }
}

How to find waterfalls you already have

Waterfalls rarely announce themselves; the page is just slower than it should be. To find them:

  1. Log or trace each data call with timings. Next.js supports OpenTelemetry through its instrumentation hook, and spans laid out on a timeline make sequential queries obvious: they form a staircase instead of a stack.
  2. Read the code from the page down. Every await in a parent that a child does not need is a candidate for Promise.all or a promise passed down.
  3. Watch the streamed response. If the shell arrives quickly but one section is always last by a wide margin, that section's queries are your target.

Fixing the biggest staircase usually does more for a slow page than any caching layer, and it also lowers database load.

When a client data library still makes sense

Server Components do not replace everything. Keep a library like TanStack Query or SWR when the browser needs to own the data lifecycle:

  • Polling or frequently refreshing data, like job progress or dashboards.
  • Infinite scroll and paginated feeds loaded as the user scrolls.
  • Heavy client-side filtering, sorting or offline support.
  • Optimistic updates across many components.

A common hybrid: the Server Component loads the first page of data, and the client library takes over for subsequent pages. Our guide to React state management covers how server state and client state split in practice, and if the data sits behind a GraphQL API, when GraphQL is the right call covers where that fits.

Mutations belong in Server Actions

For writes, Server Actions let a form or button call server code directly, then invalidate the affected data so the next render is fresh.

// app/projects/actions.ts
"use server";
 
import { z } from "zod";
import { updateTag } from "next/cache";
import { requireUser } from "@/lib/session";
import { db } from "@/lib/db";
 
const Rename = z.object({ id: z.string().uuid(), name: z.string().min(1).max(80) });
 
export async function renameProject(input: unknown) {
  const user = await requireUser();
  const { id, name } = Rename.parse(input);
 
  await db.project.updateMany({
    where: { id, ownerId: user.id },
    data: { name },
  });
  updateTag(`project-${id}`);
}

Authenticate, validate, scope the write to the user, then invalidate. If the project data is not cached with a tag, revalidatePath on the affected route does the job instead. Either way there is no client refetch hook and no manual cache juggling. The read pattern and the write pattern stay symmetric, which is most of why this model is pleasant once it clicks.

Common mistakes

  • Calling your own API routes from Server Components. It adds a network hop and a public endpoint for no benefit. Call the data function directly.
  • Sequential awaits for independent data. The page pays for the sum of the queries instead of the slowest.
  • One giant Suspense boundary, so the slowest query decides when anything appears.
  • Fetching in useEffect data that the server could load before the HTML is sent.
  • Leaking fields by passing whole rows to Client Components.
  • Slow queries hidden behind streaming. Suspense hides latency; it does not remove it. Check query plans and add the indexes your filters need.
  • Unhandled failures. A thrown error in a streamed component needs an error boundary near it. Our post on error handling patterns in React covers where to put them.

The short version

Fetch data in the component that renders it, through a server-only data layer that checks access. Parallelize anything independent, push slow sections behind Suspense so they stream, wrap shared reads in React cache, and keep Client Components at the leaves with plain data. Do that and most of the "where does my data fetching go?" anxiety disappears.

If your team is mid-migration to the App Router and the waterfalls are biting, or you want an App Router codebase built this way from the start, talk to us.

FAQ ยท 05 questions

Frequently asked questions

Can React Server Components fetch data directly from a database?

Yes. Server Components run only on the server, so they can be async and call your database or ORM directly during render. The query code and credentials never reach the browser. Put that access in a server-only data layer that also checks authorization.

How do I avoid waterfalls in React Server Components?

Start independent requests at the same time and await them together with Promise.all, or start a promise in a parent and pass it to children. Collapse dependent queries into one where your database allows it. Then move slow, independent sections behind Suspense so they stream instead of blocking the page.

Do I still need React Query or SWR with Server Components?

Often not for initial page data, which Server Components load before the HTML is sent. A client data library still earns its place for polling, infinite scrolling, offline support and screens with a lot of client-side filtering or optimistic updates. Many apps end up using both, each where it fits.

What is the difference between React cache and Next.js caching?

React cache() deduplicates calls within a single server request, so the same query called from several components runs once. Next.js caching, through 'use cache' or fetch cache options, stores results across requests and users until they expire or are invalidated. They solve different problems and are often used together.

How do I pass server data to a Client Component?

Pass it as props. Anything passed must be serializable, such as strings, numbers, plain objects, arrays and dates, so send only the fields the component needs. You can also pass an unresolved promise and read it in the Client Component with React's use hook inside a Suspense boundary.

Related service

React Development Services

Maintainable React interfaces and applications.

Learn more

Next step

Want this built right?

This is the work we do every day. Tell us what you are building and we will show you exactly how we would ship it.

First reply
Within 1 business day
Typical start
1โ€“2 weeks
Pricing
Fixed price per phase
You own
All code and accounts