Server components
Overview
Everything in this course so far has been client-side React: your components download to the browser as JavaScript and run there. React Server Components (RSC) add a second environment: components that run on the server — at build time or per request — and send only their rendered result to the browser. They let you fetch data next to your database, keep large libraries out of the bundle, and send less JavaScript to users.
Server Components require a framework that supports them — most commonly Next.js (App Router), and also React Router’s framework mode and others. You can’t add them to a plain Vite single-page app. This lesson explains the model so you’re ready when you use one.
Two kinds of components
| Server Components | Client Components | |
|---|---|---|
| Where they run | server or build | server (for the initial HTML) and browser |
Can be async, read DBs/files/secrets |
✓ | ✗ |
useState, useEffect, event handlers |
✗ | ✓ |
Browser APIs (window, localStorage) |
✗ | ✓ |
| Their code in the JS bundle | ✗ | ✓ |
In frameworks that support RSC, components are Server Components by default. You opt into the client with a directive.
A Server Component
// app/courses/page.jsx (Next.js App Router)
import { db } from '@/lib/db';
export default async function CoursesPage() {
const courses = await db.course.findMany({ orderBy: { title: 'asc' } });
return (
<main>
<h1>Courses</h1>
<ul>
{courses.map((c) => <li key={c.id}>{c.title}</li>)}
</ul>
</main>
);
}Notice what’s missing: no useEffect, no loading state, no fetch('/api/courses'), no API route. The component is async and simply awaits the data. Database credentials stay on the server. If it used a 200 KB Markdown library to render course descriptions, that library would never reach the browser.
Client Components and ‘use client’
Interactivity needs a Client Component. Put 'use client' at the top of the file:
// app/courses/LikeButton.jsx
'use client';
import { useState } from 'react';
export function LikeButton({ initialLikes }) {
const [likes, setLikes] = useState(initialLikes);
return <button onClick={() => setLikes(likes + 1)}>♥ {likes}</button>;
}// app/courses/[slug]/page.jsx — a Server Component using it
import { LikeButton } from '../LikeButton';
export default async function CoursePage({ params }) {
const { slug } = await params;
const course = await getCourse(slug);
return (
<>
<h1>{course.title}</h1>
<LikeButton initialLikes={course.likes} />
</>
);
}'use client' marks a boundary: that module, and everything it imports, becomes part of the client bundle. Client Components are still rendered to HTML on the server for the first load (so the page isn’t blank), then hydrated in the browser to become interactive.
Keep the boundary low
Put 'use client' on the smallest interactive pieces — the button, the search box, the carousel — not on whole pages. Everything above the boundary stays server-only and ships no JavaScript.
Rules at the boundary
- Props must be serialisable: strings, numbers, booleans, plain objects and arrays, dates, promises — not functions or class instances. (Server Functions are the exception, below.)
- A Client Component can’t import a Server Component, but a Server Component can pass one to a Client Component as
childrenor another prop:
// Server Component
<Tabs> {/* client: manages which tab is active */}
<CourseReviews id={id} /> {/* server: reads the database */}
</Tabs>- Context providers are Client Components; wrap them in a small
'use client'file and render them from your server layout.
Server Functions
How does a client button change data on the server? With Server Functions (called Server Actions in Next.js), marked with 'use server':
// app/actions.js
'use server';
import { revalidatePath } from 'next/cache';
export async function addReview(courseId, formData) {
const user = await getCurrentUser();
if (!user) throw new Error('Not signed in');
const text = String(formData.get('text') ?? '').trim();
if (text.length < 10) return { error: 'Reviews need at least 10 characters' };
await db.review.create({ data: { courseId, userId: user.id, text } });
revalidatePath(`/courses/${courseId}`);
return { error: null };
}The framework turns each exported function into an endpoint. Client code imports and calls it like a normal async function; React sends the request for you. They plug straight into the form features from Form actions:
'use client';
import { useActionState } from 'react';
import { addReview } from '@/app/actions';
export function ReviewForm({ courseId }) {
const [state, formAction, isPending] = useActionState(
(prev, formData) => addReview(courseId, formData),
{ error: null }
);
return (
<form action={formAction}>
<textarea name="text" />
{state.error && <p role="alert">{state.error}</p>}
<button disabled={isPending}>Post review</button>
</form>
);
}A Server Component can also pass a Server Function directly to a <form action> — and that form works even before JavaScript has loaded (progressive enhancement).
Security: a Server Function is a public HTTP endpoint. Anyone can call it with any arguments. Always check authentication and authorisation, and validate inputs, inside the function.
Streaming with Suspense
Server Components work with Suspense: the server sends the page shell immediately and streams slower parts as they finish:
export default async function CoursePage({ params }) {
const { slug } = await params;
const course = await getCourse(slug); // fast
return (
<>
<h1>{course.title}</h1>
<Suspense fallback={<ReviewsSkeleton />}>
<Reviews courseId={course.id} /> {/* async, slow — streamed in later */}
</Suspense>
</>
);
}A Server Component can also start a fetch and pass the promise to a Client Component, which reads it with use — the pattern from Suspense and use.
Should you use Server Components?
| Choose a client-rendered SPA (Vite) when… | Choose a framework with RSC when… |
|---|---|
| it’s an app behind a login (dashboards, tools) | SEO and first-load speed matter (marketing, content, e-commerce) |
| you already have a separate API | you want to query the database directly from components |
| you want the simplest hosting (static files) | you’re happy running a Node/edge server |
Everything you’ve learned — components, props, state, hooks, Suspense, forms, actions — applies in both. Server Components add a second place for code to run, not a different React.
Mental model: Server Components are for getting and showing data; Client Components are for interacting with it. Most pages are mostly server, with small islands of client.
Split a page into server and client parts
In a Next.js App Router project, write app/courses/[slug]/page.jsx as an async Server Component that loads a course with getCourse(slug) (a server-only database helper) and renders its title, description and lessons. The page should also render an interactive EnrollButton (a Client Component in its own file marked 'use client', using useState for a pending flag) that calls a Server Function enroll(courseId) defined in app/actions.js with 'use server'. Pass only the serialisable courseId to the client component.
// app/courses/[slug]/page.jsx
// app/courses/[slug]/EnrollButton.jsx
// app/actions.js// app/actions.js
'use server';
import { revalidatePath } from 'next/cache';
import { db } from '@/lib/db';
import { getCurrentUser } from '@/lib/auth';
export async function enroll(courseId) {
const user = await getCurrentUser();
if (!user) throw new Error('You must be logged in');
await db.enrolment.create({ data: { userId: user.id, courseId } });
revalidatePath('/dashboard');
}
// app/courses/[slug]/EnrollButton.jsx
'use client';
import { useState } from 'react';
import { enroll } from '@/app/actions';
export function EnrollButton({ courseId }) {
const [status, setStatus] = useState('idle');
async function handleClick() {
setStatus('pending');
try {
await enroll(courseId);
setStatus('done');
} catch {
setStatus('error');
}
}
if (status === 'done') return <p role="status">You’re enrolled!</p>;
return (
<>
<button onClick={handleClick} disabled={status === 'pending'}>
{status === 'pending' ? 'Enrolling…' : 'Enrol'}
</button>
{status === 'error' && <p role="alert">Couldn’t enrol — please try again.</p>}
</>
);
}
// app/courses/[slug]/page.jsx (a Server Component — no directive needed)
import { getCourse } from '@/lib/courses';
import { EnrollButton } from './EnrollButton';
export default async function CoursePage({ params }) {
const { slug } = await params;
const course = await getCourse(slug);
return (
<article>
<h1>{course.title}</h1>
<p>{course.description}</p>
<EnrollButton courseId={course.id} />
<ol>
{course.lessons.map((l) => <li key={l.id}>{l.title}</li>)}
</ol>
</article>
);
}Summary
- Server Components run only on the server (or at build time); their code never ships to the browser.
- They can be
asyncand read databases, files and secrets directly — no API layer needed. 'use client'marks the boundary where interactive Client Components (state, effects, events) begin.- Props passed from server to client must be serialisable; Server Components can be passed to Client Components as children.
'use server'defines Server Functions that client code and forms can call; always check auth inside them.