Module 3: Server Components & Fetching
🧊 Module 3: Server Components & Fetching
In this module, we move from useEffect data fetching and client-side state to the Server-First Data Model.
🏗️ 1. The Mechanic: Client-Side Fetching
In a traditional React app, the browser is responsible for fetching data. This creates a “Fetch Waterfall.”
🧩 The Problem: The “Fetch Waterfall”
- Browser downloads the JS bundle.
- React renders the Component.
useEffecttriggers afetchcall.- Server responds with JSON.
- React re-renders with data.
The Manual Pattern:
function Profile() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('/api/user').then(res => res.json()).then(setData);
}, []);
if (!data) return <p>Loading...</p>;
return <h1>{data.name}</h1>;
}🏗️ 2. The Abstraction: React Server Components (RSC)
Next.js components are Server Components by default. They can be async and fetch data directly from your database or API before any JavaScript is sent to the browser.
The Next.js Way:
// app/page.tsx
async function Page() {
// Direct access to your backend!
// No API endpoint or useEffect needed.
const user = await db.user.findUnique({ where: { id: 1 } });
return <h1>Welcome, {user.name}</h1>;
}🧩 The Benefit: “Zero Bundle Size”
The code for the database call and the logic to process the data never leaves the server. The browser receives only the final HTML result.
🧪 Professor’s Challenge: Streaming with Suspense
Task:
- Wrap a slow-loading component in
<Suspense fallback={<Skeleton />}>. - Observe how Next.js “streams” the shell of the page immediately and fills in the slow data once it’s ready.