Sub topic 3
Pending and Optimistic UI with Server Functions
Assume you know React components, hooks, async/await, HTML forms, and the client-server request flow. A Server Function can update data, but the interface also needs to show progress and handle the result.
Pending and optimistic updates
Use useFormStatus inside a component rendered by a <form>. It reports the status of that form submission.
Use useTransition when an event handler calls a Server Function. Use useOptimistic when the interface should show an expected result before the server confirms it.
'use client';
import { useOptimistic, useTransition } from 'react';
import { addNote } from './actions';
export function Notes({ notes }) {
const [isPending, startTransition] = useTransition();
const [optimisticNotes, addOptimistic] = useOptimistic(
notes,
(current, title) => [...current, { title, pending: true }]
);
function submit(title) {
startTransition(async () => {
addOptimistic(title);
await addNote(title);
});
}
return (
<>
<button
disabled={isPending}
onClick={() => submit('Read React documentation')}
>
{isPending ? 'Saving…' : 'Add note'}
</button>
<ul>
{optimisticNotes.map((note, index) => (
<li key={`${note.title}-${index}`}>
{note.title}{note.pending ? ' (saving)' : ''}
</li>
))}
</ul>
</>
);
}If the request fails, React can discard the optimistic state when the source data is refreshed. Do not use optimistic updates for actions where displaying an incorrect result could cause harm.
Errors and security
Return expected errors, such as invalid input, as state for useActionState to display. Throw unexpected failures so the framework’s error boundary can handle them. Do not expose database or stack details to users.
Every Server Function is a public endpoint. Validate every argument on the server, then check authentication and authorization. A hidden button or client-side check is not protection.
Binding and framework behavior
bind supplies extra arguments without placing them in hidden form fields:
const saveThisNote = updateNote.bind(null, noteId);
return <form action={saveThisNote}>...</form>;The bound value still comes from client-controlled data and must be validated. Closures also capture values when the action is created, so avoid assuming captured data remains current.
Framework bundlers must support Server Functions and coordinate the server-client boundary. After a mutation, refresh or revalidate the affected data using your framework’s cache API so the confirmed server result replaces optimistic state.
Exercise
Which hook should track a Server Function called from a button click, and which hook can display an expected new list item immediately?
Show answer
Use useTransition for the button call and useOptimistic for the immediate list update.