The All-or-Nothing Rendering Trap
In traditional Server-Side Rendering (SSR), the server must wait to fetch all the data for a page before it can generate the HTML and send it to the client. If your dashboard has a lightning-fast user profile widget but relies on a slow analytics query that takes 3 seconds, the user stares at a blank screen for 3 seconds. The slow component bottlenecks the fast ones.
At Smart Tech Devs, we build fluid, non-blocking user interfaces by leveraging React Suspense and Streaming in the Next.js App Router. This allows us to send parts of the UI to the browser immediately while the slower data fetches finish in the background.
Architecting Progressive UIs
Streaming breaks down the page’s HTML into smaller chunks. Next.js instantly delivers the static layout and wraps the slow dynamic components in a fallback state until their data resolves.
Step 1: Isolating the Data Fetch
First, we create a Server Component that handles its own asynchronous data fetching. We intentionally do not await this data at the top-level page layout.
// components/RevenueChart.tsx
import db from '@/lib/database';
export default async function RevenueChart() {
// Simulate a slow database query (e.g., 3 seconds)
const revenueData = await db.analytics.getHeavyRevenueMetrics();
return (
<div className="p-4 border rounded-xl">
<h3>Q3 Revenue</h3>
{/* Chart rendering logic using revenueData */}
</div>
);
}
Step 2: Wrapping with Suspense
In our main page component, we import the heavy component and wrap it in a <Suspense> boundary. We provide a lightweight skeleton as a fallback.
// app/dashboard/page.tsx
import { Suspense } from 'react';
import RevenueChart from '@/components/RevenueChart';
import UserProfile from '@/components/UserProfile'; // Fast component
import ChartSkeleton from '@/components/Skeletons/ChartSkeleton';
export default function DashboardPage() {
return (
<main className="grid grid-cols-2 gap-6">
{/* This renders instantly */}
<UserProfile />
{/* Next.js sends the skeleton immediately, then streams the chart in later */}
<Suspense fallback={<ChartSkeleton />}>
<RevenueChart />
</Suspense>
</main>
);
}
The Engineering ROI
By implementing Streaming and Suspense, you drastically reduce your Time To First Byte (TTFB) and First Contentful Paint (FCP). Users instantly perceive your application as lightning-fast, and slow backend queries no longer paralyze the entire frontend experience.
답글 남기기