Lesson 4 of 7
React Server Components (RSC)
React Server Components represent the biggest paradigm shift since hooks. Server Components run exclusively on the server - they can access databases and file systems directly, never ship their code to the browser, and seamlessly compose with Client Components. This is React's answer to the 'ship too much JavaScript' problem.
Server vs Client Components
// ---- Understanding RSC ----
// Server Components (default in Next.js App Router):
// - Run on server only (build time or per-request)
// - CAN: await any async operation, access DB, files, secrets (env vars)
// - CANNOT: use hooks (useState, useEffect), browser APIs, event handlers
// - Ship ZERO JavaScript to the browser
// - Serialized as a special RSC payload (not HTML, not JSON)
// ---- Server Component - fetches data directly ----
// app/users/page.tsx - server component (no 'use client')
async function UsersPage() {
// Direct database access - zero API layer needed
const users = await db.query('SELECT * FROM users ORDER BY created_at DESC LIMIT 20');
// API keys never leak to browser - they never leave the server
const config = await getServerConfig(); // reads from env directly
return (
<main>
<h1>Users ({users.length})</h1>
{/* Pass serializable props to client component */}
<UserList users={users} />
</main>
);
}
// ---- 'use client' - marks a component as client-only ----
// app/users/UserList.tsx
'use client'; // all imports from here downward run in browser
import { useState } from 'react';
interface User { id: string; name: string; email: string; }
export function UserList({ users }: { users: User[] }) {
const [filter, setFilter] = useState('');
// โ
useState works - this is a Client Component
const filtered = users.filter(u => u.name.toLowerCase().includes(filter));
return (
<>
<input value={filter} onChange={e => setFilter(e.target.value)} placeholder="Filter..." />
<ul>{filtered.map(u => <li key={u.id}>{u.name}</li>)}</ul>
</>
);
}
// ---- Composing Server + Client ----
// Server components CAN render client components (reverse is not true)
// app/products/page.tsx - server component
import { ProductFilters } from './ProductFilters'; // client component
import { ProductGrid } from './ProductGrid'; // server component
async function ProductsPage({ searchParams }: { searchParams: { category?: string } }) {
const category = searchParams.category ?? 'all';
const products = await productService.findMany({ category }); // server-only
return (
<div>
<ProductFilters /> {/* client - handles filter interaction */}
<ProductGrid products={products} /> {/* server - renders data */}
</div>
);
}
// ---- Server Actions - form handling without API routes ----
// app/users/actions.ts
'use server'; // marks functions as server actions
import { revalidatePath } from 'next/cache';
export async function createUser(formData: FormData) {
const name = formData.get('name') as string;
const email = formData.get('email') as string;
await db.users.create({ data: { name, email } });
revalidatePath('/users'); // invalidate cached page
}
// app/users/CreateUserForm.tsx
'use client';
import { createUser } from './actions';
function CreateUserForm() {
return (
<form action={createUser}> {/* {/* server action invoked on submit */}
<input name="name" required />
<input name="email" type="email" required />
<button type="submit">Create User</button>
</form>
);
}Common Mistakes - RSC
- Adding 'use client' to every component - Server Components are the default and the performance win; only add 'use client' when you need interactivity (hooks, events)
- Passing non-serializable props from server to client - functions, class instances, and circular objects can't cross the server-client boundary; only plain serializable values (strings, numbers, arrays, plain objects)
- Using context in server components - Context (React.createContext) is client-only. For server-wide data, use function arguments or Next.js's `cache()` for deduplication
- Fetching in client components when server component could do it - every client-side fetch adds latency and ships fetching code to the browser; prefer server component data fetching when the data isn't personalized
Tip
Tip
Practice React Server Components RSC in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and flow for React Server Components (RSC)
Practice Task
Note
Practice Task - (1) Write a working example of React Server Components RSC from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with React Server Components RSC is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.
Key Takeaways
- React Server Components represent the biggest paradigm shift since hooks.
- Adding 'use client' to every component - Server Components are the default and the performance win; only add 'use client' when you need interactivity (hooks, events)
- Passing non-serializable props from server to client - functions, class instances, and circular objects can't cross the server-client boundary; only plain serializable values (strings, numbers, arrays, plain objects)
- Using context in server components - Context (React.createContext) is client-only. For server-wide data, use function arguments or Next.js's `cache()` for deduplication
Finished this lesson?