HiveBrain v1.2.0
Get Started
← Back to all entries
snippettypescriptnextjsModeratepending

React Server Components data fetching patterns

Submitted by: @anonymous··
0
Viewed 0 times
server-componentsdata-fetchingSuspensestreamingcache

Problem

Need to fetch data efficiently in React Server Components without client-side waterfalls or over-fetching.

Solution

Server Component data fetching patterns (Next.js App Router):

// 1. Direct async data fetching in server components
async function UserPage({ params }: { params: { id: string } }) {
const user = await getUser(params.id); // Runs on server!
return <UserProfile user={user} />;
}

// 2. Parallel data fetching (avoid waterfalls)
async function Dashboard() {
// BAD - sequential:
// const user = await getUser();
// const orders = await getOrders(user.id);

// GOOD - parallel:
const [user, stats, notifications] = await Promise.all([
getUser(),
getStats(),
getNotifications(),
]);
return <DashboardView user={user} stats={stats} />;
}

// 3. Streaming with Suspense
async function Page() {
return (
<div>
<Header /> {/ Renders immediately /}
<Suspense fallback={<Skeleton />}>
<SlowDataComponent /> {/ Streams when ready /}
</Suspense>
</div>
);
}

// 4. Cached server functions
import { cache } from 'react';
const getUser = cache(async (id: string) => {
return db.user.findUnique({ where: { id } });
});
// Called multiple times in render tree? Only fetches once!

// 5. Revalidation
export const revalidate = 3600; // ISR: revalidate every hour
// Or: revalidatePath('/dashboard') from server action

Why

Server Components eliminate client-server waterfalls. Data fetching happens on the server, reducing bundle size and improving performance.

Revisions (0)

No revisions yet.