Sub topic 2
Calling Server Functions from Client Components
Assume you know React components, hooks, async/await, HTML forms, and the client-server request cycle. A Server Function is an asynchronous function that runs on the server. A Client Component can call it through a framework-generated request.
Calling and serializing arguments
Define the function in a module marked with "use server":
// app/actions.js
'use server';
export async function createNote(title) {
const cleanTitle = String(title ?? '').trim();
if (!cleanTitle) {
throw new Error('Title is required.');
}
// Save cleanTitle with your database here.
return { ok: true };
}Import it into a Client Component and call it from an event handler. Use startTransition when you want React to track the pending request:
'use client';
import { useTransition } from 'react';
import { createNote } from './actions';
export function AddButton() {
const [isPending, startTransition] = useTransition();
return (
<button
disabled={isPending}
onClick={() => {
startTransition(() => createNote('Read React docs'));
}}
>
{isPending ? 'Saving…' : 'Save'}
</button>
);
}Arguments and return values must use values that the framework can serialize across the network. Prefer strings, numbers, booleans, null, arrays, plain objects, and FormData. Do not pass database connections, DOM nodes, class instances, or ordinary functions. A Server Function reference is a special exception handled by the framework.
Using a Server Function as a form action
Forms can pass FormData directly to a Server Function. This can support progressive enhancement, allowing submission to begin before all client JavaScript finishes loading.
<form action={createNote}>
<input name="title" required />
<button type="submit">Add note</button>
</form>Returning validation state with `useActionState`
For expected failures, return state instead of throwing. useActionState supplies the previous state and gives the component the latest result:
// app/actions.js
'use server';
export async function createNote(previousState, formData) {
const title = String(formData.get('title') ?? '').trim();
if (!title) {
return { error: 'Enter a title.' };
}
return { error: null };
}'use client';
import { useActionState } from 'react';
import { createNote } from './actions';
export function NoteForm() {
const [state, formAction, isPending] = useActionState(createNote, {
error: null,
});
return (
<form action={formAction}>
<input name="title" />
<button disabled={isPending}>Add note</button>
{state.error && <p role="alert">{state.error}</p>}
</form>
);
}Exercise
In a useActionState Server Function, what are the first two arguments?
Show answer
The previous state and the submitted FormData.