Sub topic 1
Where Server and Client Components run
Prerequisites.
This chapter assumes solid knowledge of React components, props, state, and hooks. You should also know async/await, HTML forms, FormData, and the basic client-server request flow.
Where Server and Client Components run
A Server Component runs on the server. It can read server-only resources, such as a database, and its rendered result is sent to the client. Its code does not become browser JavaScript.
A Client Component runs in the browser. It can use interactive hooks such as useState and respond to events. A file becomes a Client Component when its first statement is the 'use client' directive. This directive marks a client boundary. Imported modules below that boundary are included in the client bundle.
What `"use server"` marks
The 'use server' directive marks an asynchronous function as a Server Function. The function runs on the server even when client code invokes it. A framework or bundler turns the call into a network request.
The directive does not make a component interactive, move arbitrary code to the server, or replace authentication. 'use client' and 'use server' mark different boundaries.
Server Functions and Server Actions: terminology
Server Function is the current general term for an async function that client code can invoke on the server. Server Action is an older or narrower term that is still common, especially for a Server Function used as a form or transition action. The important behavior is where the function runs and how its arguments cross the boundary.
Defining Server Functions
You can define one inline in a Server Component:
export default function Page() {
async function createNote(formData) {
'use server';
const title = String(formData.get('title') ?? '').trim();
return { title };
}
return (
<form action={createNote}>
<input name="title" required />
<button type="submit">Add note</button>
</form>
);
}For reuse, place exported functions in a module with a file-level directive:
// app/actions.js
'use server';
export async function createNote(formData) {
const title = String(formData.get('title') ?? '').trim();
return { title };
}Exercise
Which directive marks a module as a client boundary, and which directive marks an async function as a Server Function?
Show answer
'use client' marks the client boundary. 'use server' marks the Server Function.