Sub topic 5
Calling Server Functions from Client Components
This chapter assumes you know React hooks, async/await, and the difference between Server and Client Components. It also assumes you have seen the "use server" directive and know how to define a Server Function. Here you will learn how a Client Component gets a Server Function and what happens when it calls one.
What the client actually holds
A Client Component runs in the browser. The code of a Server Function never reaches the browser. When the bundler sees a Client Component import from a "use server" file, it replaces each exported function with a small stub. The stub holds a reference ID that the framework can map back to the real function on the server.
Calling the stub looks like a normal async call:
const result = await deleteNote(noteId);Behind that line, the framework does the following:
- It serializes the arguments.
- It sends an HTTP POST request to the server, with the reference ID attached.
- The server looks up the function, runs it, and serializes the return value.
- The client receives the response and resolves the Promise.
Three consequences follow from this model:
- The call is always asynchronous, even if the server function body has no
await. Treat the result as a Promise. - The call is a network request. It can be slow, can fail, and can be interrupted by a lost connection.
- The server function is an endpoint. Anyone who can send an HTTP request can try to call it, which the security chapter covers in detail.
Two ways to get a Server Function into a Client Component
Import it from a `"use server"` file
This is the most direct route. The Client Component imports the function by name, as it would any module:
// app/DeleteButton.js
'use client';
import { useTransition } from 'react';
import { deleteNote } from './actions';
export function DeleteButton({ noteId }) {
const [isPending, startTransition] = useTransition();
return (
<button
disabled={isPending}
onClick={() => {
startTransition(async () => {
await deleteNote(noteId);
});
}}
>
{isPending ? 'Deleting…' : 'Delete'}
</button>
);
}The actions.js file must start with 'use server'. If it does not, the bundler treats deleteNote as ordinary code and bundles it into the browser, where db and getSession do not exist.
Receive it as a prop from a Server Component
A Server Component can import a Server Function and hand it to a Client Component as a prop. Ordinary functions cannot cross the Server to Client boundary. A Server Function can, because React serializes it as the reference described above.
// app/page.js (a Server Component)
import { deleteNote } from './actions';
import { ConfirmDelete } from './ConfirmDelete';
export default function Page() {
return <ConfirmDelete noteId="n_42" onConfirm={deleteNote} />;
}// app/ConfirmDelete.js
'use client';
import { useState, useTransition } from 'react';
export function ConfirmDelete({ noteId, onConfirm }) {
const [confirming, setConfirming] = useState(false);
const [isPending, startTransition] = useTransition();
if (!confirming) {
return <button onClick={() => setConfirming(true)}>Delete…</button>;
}
return (
<button
disabled={isPending}
onClick={() => startTransition(async () => {
await onConfirm(noteId);
})}
>
Really delete
</button>
);
}The prop approach keeps the Client Component reusable. It does not need to know which module the function comes from. This also works for an inline function with a function-level 'use server' directive defined inside the Server Component. A function defined that way can close over values, which has its own rules (see the chapter on bind and closures).
What you cannot do
You cannot write a function with 'use server' inside a Client Component, and you cannot put the file-level directive in a file that also has 'use client'. The two directives mark opposite sides of the boundary. A file is one or the other.
Choosing how to call: form, handler, or effect
A Server Function can be invoked from several places. This chapter focuses on event handlers. The next chapter covers forms.
| Call site | Typical use | Pending state | Notes |
|---|---|---|---|
| Form `action` prop | Submitting form data | `useFormStatus`, `useActionState` | Works before JavaScript loads in supporting frameworks |
| Event handler | Buttons, toggles, drag and drop | `useTransition` | You pass the arguments yourself |
| `useEffect` | Rarely appropriate | Manual | Avoid for reads, see below |
An event handler gives you full control over the arguments. The cost is that you must manage state yourself. That is why the handler calls are wrapped in startTransition.
Why wrap the call in a transition
You can call a Server Function in a plain handler:
onClick={async () => {
await deleteNote(noteId);
}}This works, but React has no way to know that work is in progress. You would need your own useState flag to disable the button. Calling it inside startTransition gives you three things:
isPendingistruefor the whole duration of the async function, including the network round trip.- If the framework refreshes the page data after the mutation (for example, by revalidating a path), the UI update is part of the same transition. The pending flag stays on until the new UI is ready.
- The current UI stays interactive and visible instead of being replaced by a Suspense fallback.
Async functions in startTransition are supported in React 19. In earlier versions, the callback must be synchronous and the pattern above does not apply.
Using the return value
The call resolves to whatever the server function returned, as long as the value is serializable. A Client Component can use it directly:
// app/actions.js
'use server';
export async function likeNote(noteId) {
// ...update the database...
return { likes: 17 };
}// app/LikeButton.js
'use client';
import { useState, useTransition } from 'react';
import { likeNote } from './actions';
export function LikeButton({ noteId, initialLikes }) {
const [likes, setLikes] = useState(initialLikes);
const [isPending, startTransition] = useTransition();
return (
<button
disabled={isPending}
onClick={() => {
startTransition(async () => {
const result = await likeNote(noteId);
startTransition(() => setLikes(result.likes));
});
}}
>
{likes} likes
</button>
);
}Note the nested startTransition around setLikes, which follows the warning above. For forms, useActionState is the better tool for returning state. It is covered in a later chapter.
Behavior to expect at runtime
- Sequential dispatch. In current React frameworks, calls from one client are queued and sent one at a time. If a user clicks twice quickly, the second request waits for the first. Do not rely on this for correctness, and do not use Server Functions to fetch data in parallel. Use a Server Component, a route handler, or a data library for reads.
- No built-in caching or deduplication. Every call is a new POST request.
- Return values are copies. The client gets a deserialized copy of the result. Class instances, functions, and other non-serializable values cannot be returned. The serialization chapter lists the allowed types.
- Errors reject the Promise. If the function throws, the awaited call throws on the client. In production, frameworks replace the error message with a generic one so that server details do not leak. The error handling chapter covers what to do about it.
- Stale references. If you deploy a new version while a user has an old page open, the IDs in the old page may no longer exist on the server. Frameworks handle this differently, and some provide a deployment-skew setting. Expect occasional failures after a deploy.
Common mistakes
- Forgetting
await. Without it, the transition ends before the request does, andisPendingflips back tofalsetoo early. Errors become unhandled Promise rejections. - Importing a non-
"use server"module and expecting it to run remotely. An import from an ordinary file runs in the browser. Check the first line of the file. - Passing a plain function as a prop from a Server Component. React throws a serialization error. Only Server Functions may cross.
- Using a Server Function as a data source on render. Calling one in
useEffectto load data creates a POST for every mount and bypasses the framework's data loading. - Trusting the arguments. The client chooses the arguments. A hidden
noteIdis still user input.
Exercise
A Client Component imports saveDraft from ./actions and calls it in a button handler with await saveDraft(text). The button should be disabled while the request runs. What do you change, and why is startTransition preferable to a hand-written useState flag when the framework refreshes data after the mutation?
Show answer
Get [isPending, startTransition] = useTransition(), call startTransition(async () => { await saveDraft(text); }), and set disabled={isPending}. The transition keeps isPending true until the async function finishes, and in frameworks that refresh data after a mutation, until the refreshed UI is ready. A manual flag would turn off as soon as the response arrived, before the new UI was shown. A transition also keeps the old UI visible instead of showing a Suspense fallback.
Exercise
Why does passing onConfirm={deleteNote} from a Server Component to a Client Component work, while passing onConfirm={() => console.log('hi')} fails?
Show answer
A Server Function is serialized as a reference ID that the framework can send over the network and resolve on the server. An ordinary function has no such reference and cannot be serialized, so React rejects it at the Server to Client boundary.