The short answer: React Server Components (RSC) are components that run only on the server, during the build or a request. They can read databases and files directly, keep secrets and heavy libraries off the client, and send no JavaScript of their own to the browser. Client Components, marked with the
'use client'directive, are the interactive parts that also run in the browser and can use state, effects and event handlers. The skill is drawing the boundary: keep most of the page on the server, push'use client'down to small interactive leaves, pass only serialisable props across, and use Server Functions for mutations.
For most of React's history, every component you wrote ended up in the browser. Even a component that just rendered a list of blog post titles shipped its code to the user, ran there, and often fetched its data there too, after the page loaded. Server-side rendering helped with the first paint, but the same code still had to be downloaded and run again in the browser to make the page interactive.
React Server Components change that default. Some components now run only on the server, and their code never reaches the browser at all. In frameworks such as Next.js's App Router, they're the default: every component is a Server Component unless you say otherwise. That shift trips up a lot of developers, because familiar patterns (a useState here, an onClick there) suddenly produce errors, and the reasons aren't obvious at first.
This guide explains the mental model, where the boundary between server and client sits and why, how data fetching and mutations work, how streaming fits in, and the mistakes that cause most of the confusion. Examples use Next.js, the most widely used RSC framework, but the concepts are React's.
The mental model in one paragraph
Think of your component tree as having two environments. Server Components run on the server and produce a description of the UI, which React sends to the browser in a compact serialised format. Client Components run on the server for the initial HTML too, and then in the browser, where they become interactive. Server Components can render Client Components and pass them props. The browser receives the rendered output of Server Components, but only the code of Client Components. So the more of your tree stays on the server, the less JavaScript the user downloads.
Server Components: what they can and can't do
A Server Component is an ordinary function component that runs on the server. It can be async, which means it can await data directly:
// app/blog/[slug]/page.tsx (a Server Component by default)
import { db } from "@/lib/db";
import { LikeButton } from "./like-button";
export default async function PostPage({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params;
const post = await db.post.findUnique({ where: { slug } });
if (!post) return <p>Not found</p>;
return (
<article>
<h1>{post.title}</h1>
<div dangerouslySetInnerHTML={{ __html: post.html }} />
<LikeButton postId={post.id} initialCount={post.likes} />
</article>
);
}
Things Server Components are good at:
- Reading data directly from a database, the file system or an internal API, without building a separate API route for the browser to call.
- Keeping secrets on the server. API keys and database credentials used in a Server Component never reach the client.
- Using heavy libraries for free. A Markdown parser, a syntax highlighter or a date library used only in Server Components adds nothing to the browser bundle.
- Reducing waterfalls. Data loads on the server, close to the database, rather than in a series of browser requests after the page arrives.
Things they can't do, because they never run in the browser: use state (useState, useReducer), use effects (useEffect), attach event handlers such as onClick, or use browser-only APIs like window and localStorage. React's documentation on Server Components covers the full set of rules.
Client Components and the 'use client' boundary
When you need interactivity, you write a Client Component by putting the 'use client' directive at the very top of the file:
// app/blog/[slug]/like-button.tsx
"use client";
import { useState, useTransition } from "react";
import { likePost } from "./actions";
export function LikeButton({ postId, initialCount }: { postId: string; initialCount: number }) {
const [count, setCount] = useState(initialCount);
const [pending, startTransition] = useTransition();
return (
<button
disabled={pending}
onClick={() => startTransition(async () => setCount(await likePost(postId)))}
>
♥ {count}
</button>
);
}
The directive's meaning is easy to misread. It doesn't mark one component; it marks a boundary in the module graph. According to React's 'use client' reference, the file with the directive and everything it imports (its transitive dependencies) are treated as client code. So if your Client Component imports a big utility module, that whole module ships to the browser. You don't need 'use client' in every interactive file, only at the entry points where server code hands over to client code.
Push the boundary down
The most valuable habit with RSC is keeping 'use client' as low in the tree as possible. If a whole page is a Client Component because one button needs an onClick, everything on that page ships as JavaScript. Instead, keep the page and its layout on the server and extract the interactive part into a small Client Component, like the like button above. The article text, the comments list and the layout stay on the server, and the browser downloads only the button's code.
Passing data across the boundary
When a Server Component renders a Client Component, its props have to travel from the server to the browser. That means they must be serialisable. Strings, numbers, booleans, plain objects and arrays, dates, and a few other built-in types work. Class instances, such as an ORM model object with methods, do not. Functions can't be passed either, with one exception: Server Functions, covered below.
Two practical consequences follow. First, pass plain data, not rich objects: map your database row to a plain object with just the fields the component needs. Second, be careful what you pass. Props sent to a Client Component end up in the page's payload, visible to anyone who views the source. Passing a whole user record because one component needs the name can leak an email address, an internal ID or worse. Select only what's needed.
Server Components inside Client Components
A Client Component can't import a Server Component, because the client module graph would pull it into the browser. But it can render one that's passed to it as a prop, most commonly as children:
// A client-side collapsible panel that wraps server-rendered content.
// page.tsx (server):
<Collapsible title="Comments">
<CommentsList postId={post.id} /> {/* a Server Component */}
</Collapsible>
The Server Component is rendered on the server, and its output is slotted into the Client Component. This "children" pattern is how you mix interactive wrappers (tabs, modals, accordions) with server-rendered content without turning the content into client code.
Mutations with Server Functions
Reading data is easy in Server Components. Writing it needs a way for the browser to call back to the server. Server Functions do this: async functions marked with the 'use server' directive that run on the server but can be called from Client Components, or used as a form's action.
// app/blog/[slug]/actions.ts
"use server";
import { db } from "@/lib/db";
import { getSession } from "@/lib/auth";
export async function likePost(postId: string): Promise<number> {
const session = await getSession();
if (!session) throw new Error("Not signed in");
const post = await db.post.update({
where: { id: postId },
data: { likes: { increment: 1 } },
});
return post.likes;
}
Under the hood, the framework turns each Server Function into an endpoint the client can call. That's convenient, and it's also the most important security point in this guide: a Server Function is a public HTTP endpoint. Anyone can call it with any arguments, not just your UI. Always check authentication and authorisation inside the function, and validate every argument, exactly as you would in an API route. Hiding a button doesn't protect the action behind it.
Server Functions also work with plain HTML forms, which means a form can submit and work even before JavaScript has loaded, a nice progressive-enhancement property. React's hooks such as useActionState and useFormStatus help show pending states and results.
Streaming and Suspense
Because Server Components can be async, a page might wait on several data sources. Rather than blocking the whole page on the slowest one, you can wrap slow parts in <Suspense> with a fallback. The server sends the rest of the page immediately and streams in each suspended section as its data arrives.
import { Suspense } from "react";
export default async function Dashboard() {
return (
<>
<Header /> {/* fast: renders right away */}
<Suspense fallback={<ChartSkeleton />}>
<RevenueChart /> {/* slow query: streams in later */}
</Suspense>
<Suspense fallback={<ListSkeleton />}>
<RecentOrders />
</Suspense>
</>
);
}
Place boundaries around independent, slow pieces, not around everything; too many skeletons make a page feel jumpy. And start independent fetches in parallel: two sequential awaits in one component create a waterfall, while starting both promises first and awaiting them together, or splitting them into sibling components under separate Suspense boundaries, lets them overlap. Streaming AI responses is a related but different problem, covered in the guide to streaming LLM responses in Next.js.
Caching and freshness
Since Server Components fetch data on the server, the framework's caching decides how fresh that data is. Next.js offers several layers, from static rendering at build time, through time-based revalidation, to fully dynamic rendering on every request, and its caching APIs have changed across major versions. The practical advice is version-independent: decide per route how fresh the data must be, make that explicit in code rather than relying on defaults you haven't checked, and after a mutation in a Server Function, revalidate the paths or tags whose data changed so users see their own update immediately.
For per-request deduplication, React's cache function memoises a data-loading function within a single render, so several components can ask for the same user or post without causing duplicate database queries.
Common mistakes and how to fix them
- "useState only works in Client Components." You used a hook in a Server Component. Move the interactive part into a small Client Component rather than marking the whole file
'use client'. - "Event handlers cannot be passed to Client Component props." A Server Component tried to pass an
onClickfunction. Put the handler inside a Client Component, or use a Server Function. - Accidentally shipping a huge bundle. A
'use client'file imports a large library or a shared utility module that drags in more. Check bundle analysis, and keep heavy work in Server Components. - Leaking server-only code. A module containing secrets gets imported from a Client Component. The
server-onlypackage makes such imports fail at build time; addimport "server-only"to modules that must never reach the client. - Passing non-serialisable props. ORM objects, class instances and functions fail or lose behaviour. Map to plain objects.
- Unprotected Server Functions. An action that updates data without checking who's calling. Every Server Function needs its own auth and validation.
- Browser APIs during server render. Client Components still render on the server for the initial HTML, so code that touches
windowat the top level fails there. Access browser APIs inside effects or event handlers.
A worked example: refactoring a client-heavy page
Consider a product page built the old way: a single Client Component that fetches the product in a useEffect, shows a spinner, then renders the description, specifications, reviews and an "add to cart" button. The user downloads the whole page's code, waits for it to run, then waits again for the fetch.
Refactored with Server Components:
- The page becomes an async Server Component that loads the product directly from the database. No effect, no spinner for the main content, and the description renders into the initial HTML, which is also better for search engines.
- Specifications and description stay on the server. A Markdown renderer used for the description adds nothing to the bundle.
- Reviews move under a Suspense boundary, because they come from a slower service. The page appears immediately, and reviews stream in.
- "Add to cart" becomes a small Client Component that calls a Server Function, which checks the session, validates the quantity and updates the cart.
- The image gallery, if it has swiping and zoom, is a Client Component that receives a plain array of image URLs as props.
The result typically ships far less JavaScript, shows content sooner and removes an API route that existed only to serve the old client fetch. The interactive parts work exactly as before.
Limits of the server-first approach
Server Components are a strong default for content-heavy pages, dashboards and most product pages. They're less of a win for highly interactive applications where nearly everything responds to user input in real time, such as editors, design tools or games. In those, most of the tree needs to be client code anyway, and Server Components mostly help with the shell and initial data. That's fine. RSC doesn't require that everything be on the server; it gives you the choice per component.
It's also worth knowing that RSC needs framework support for bundling, routing and the server runtime. Next.js's App Router is the most mature option, and other frameworks are adding support. If your app is a pure single-page application served as static files with no server, Server Components aren't available without changing how you deploy.
Testing Server and Client Components
Testing changes a little in an RSC codebase, mostly because async Server Components don't fit neatly into older component-testing tools. A practical split works well:
- Unit-test the logic, not the component. Data loading, permission checks and formatting in Server Components are best extracted into plain functions, which you can test directly without rendering anything.
- Test Client Components as before. Interactive components with state and events work with familiar component-testing libraries, given plain props.
- Test Server Functions like API handlers. Call them with valid and invalid arguments, signed in and signed out, and assert on the results and the database changes. This is where authorisation bugs hide.
- Use end-to-end tests for the whole page. A browser-based test that loads the real page covers the server and client together, including streaming and hydration, which unit tests can't reproduce faithfully.
This approach also nudges the code into a good shape: thin components that render, with the real work in functions that are easy to test and reuse.
Security habits for server-first code
Moving code to the server removes some risks and adds a few new ones, mostly because the line between "server" and "client" is now a directive in a file rather than a separate codebase. A few habits keep that line solid.
- Mark server-only modules. Any module that reads secrets, talks to the database or calls internal services should import the
server-onlypackage. If a Client Component ever imports it, directly or through a chain of imports, the build fails instead of quietly shipping that code to the browser. - Use a data access layer. Rather than calling the database from components all over the codebase, route reads and writes through a small set of functions that check the current user's permissions and return only the fields the UI needs. Components then can't accidentally fetch or pass more than they should.
- Return data transfer objects, not rows. Map database results to plain objects with explicit fields before passing them to Client Components. That's required for serialisation anyway, and it's the moment to drop sensitive fields.
- Authorise in every Server Function. Never assume that because a button is only shown to admins, only admins can call its action.
- Keep environment variables straight. In Next.js, only variables prefixed with
NEXT_PUBLIC_are exposed to the browser. Keep secrets unprefixed, and be suspicious of any code that moves a secret into a prop.
These habits matter most in larger teams, where the person adding 'use client' to a file may not know what its imports eventually pull in. Making the dangerous mistakes fail at build time is far more reliable than catching them in review.
Performance: what actually improves
Server Components are often described as "faster," which is true in specific ways worth understanding, so you can measure the right things.
Less JavaScript. Components that stay on the server ship no code to the browser, and neither do the libraries they use. On content-heavy pages this can remove a large share of the bundle, which matters most on slower phones, where parsing and running JavaScript is often the bottleneck rather than the download itself.
Fewer round trips. Data is fetched on the server, near the database, during rendering, rather than by the browser after the page loads. That removes the classic pattern of HTML, then JavaScript, then an API request, then a render.
Earlier content. With streaming, the server sends the parts of the page that are ready while slower parts are still loading, so users see meaningful content sooner.
What doesn't automatically improve is server work. Rendering on the server costs server time, and slow database queries are now on the critical path of the page. Watch server response times and query performance alongside browser metrics such as Largest Contentful Paint and Interaction to Next Paint, and cache data that doesn't need to be fresh on every request.
Frequently asked questions
What are React Server Components?
React Server Components are components that run only on the server, either at build time or per request. They can read data directly from databases and files, keep secrets and heavy libraries off the client, and send no JavaScript of their own to the browser. Interactive parts are written as Client Components and combined with them.
What is the difference between Server and Client Components?
Server Components run only on the server and can't use state, effects, event handlers or browser APIs, but they can be async and access server resources. Client Components, marked with the use client directive, render on the server for initial HTML and then run in the browser, where they can use state, effects and events.
When should I use the use client directive?
Use it only at the entry point of interactive parts of your UI, such as buttons, forms with local state, or components that use browser APIs. Keep it as low in the tree as possible, because the marked file and everything it imports become client code shipped to the browser.
Can Server Components use hooks like useState or useEffect?
No. Server Components don't run in the browser, so they can't use state or effect hooks or attach event handlers. Move that logic into a small Client Component and render it from the Server Component, passing serialisable props.
Are Server Functions secure?
Only if you make them secure. A Server Function becomes an endpoint that anyone can call with any arguments, not just your UI. Check authentication and authorisation inside every Server Function and validate all inputs, exactly as you would in an API route.
The takeaway
React Server Components flip the default from "everything runs in the browser" to "only the interactive parts do." Once that clicks, the rules make sense: Server Components fetch and render, Client Components handle interaction, props crossing the boundary must be plain data, and Server Functions are public endpoints that need real security checks. Keep the client boundary small and low in the tree, and you get pages that load faster, ship less JavaScript and keep secrets where they belong.
Author at LuminaryEra
The LuminaryEra editorial desk publishes long-form, hands-on guides on AI-assisted development, large language models, developer tools and web engineering. Articles are researched and drafted with the help of AI tools, link to their sources, and are corrected when readers report errors.
View all articles





