Next.jsMedium
What is the difference between use server and use client?
"use client" marks a module as client code: its components are bundled for the browser and can use state and effects. "use server" marks functions as Server Functions: they stay on the server and the client gets a reference it can call over the network. Neither is needed to make a Server Component; that is the default.
"use client"
- Placed at the top of a file.
- Declares a boundary in the module graph: this file and its imports go to the client bundle.
- Components inside are still SSR'd to HTML, then hydrated.
- Used for interactivity, hooks and browser APIs.
"use server"
- Placed at the top of a file (all exports are Server Functions) or as the first line of an async function.
- The function body never ships to the client. The client gets an encrypted action ID.
- Calls become POST requests; arguments and return values are serialized.
- Used for mutations: form submissions, updates, deletes, with revalidation.
Mental model
"use client": "send this code to the browser.""use server": "let the browser call this code on the server."
Common mistakes
- Adding
"use server"to a component file to make it a Server Component. It is unnecessary and turns exports into endpoints. - Exporting non-async values from a
"use server"file. - Assuming
"use server"functions are private. They are public endpoints; authorize inside them. - Using
"use server"as a data-fetching layer for reads. Server Functions run sequentially, so reads are better in Server Components.
Related directives
"use cache", "use cache: private" and "use cache: remote" (Cache Components) mark cacheable functions and components.
Code example
tsx
1// app/actions.ts - functions the client can call2"use server";34import { updateTag } from "next/cache";5import { verifySession } from "@/lib/auth";6import { db } from "@/lib/db";78export async function likePost(postId: string) {9 const user = await verifySession();10 await db.like.create({ data: { postId, userId: user.id } });11 updateTag(`post:${postId}`);12}1314// app/like-button.tsx - code that runs in the browser15// "use client";16// import { useTransition } from "react";17// import { likePost } from "./actions"; // imports a reference, not the server code18// export function LikeButton({ postId }: { postId: string }) {19// const [pending, start] = useTransition();20// return <button disabled={pending} onClick={() => start(() => likePost(postId))}>Like</button>;21// }
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.