Sub topic 3
Optimistic UI with `useOptimistic`
Assume you know React function components, hooks, JSX, async functions, fetch, and the browser FormData API. This chapter connects useOptimistic with form Actions and Server Functions.
Optimistic UI with `useOptimistic`
Optimistic UI shows the result of a mutation before the server confirms it. React displays temporary state while an Action runs. When the Action finishes, the component receives the real data and the temporary state disappears.
import { useOptimistic, useRef } from "react";
export function Thread({ messages, sendMessage }) {
const formRef = useRef(null);
const [visibleMessages, addOptimisticMessage] = useOptimistic(
messages,
(currentMessages, text) => [
...currentMessages,
{ id: `pending-${currentMessages.length}`, text, sending: true },
]
);
async function submitMessage(formData) {
const text = String(formData.get("message") ?? "").trim();
if (!text) return;
addOptimisticMessage(text);
formRef.current.reset();
await sendMessage(text);
}
return (
<>
<ul>
{visibleMessages.map((message) => (
<li key={message.id}>
{message.text}
{message.sending && <small> (Sending...)</small>}
</li>
))}
</ul>
<form action={submitMessage} ref={formRef}>
<input name="message" />
<button type="submit">Send</button>
</form>
</>
);
}The first argument is the real value from the parent. The second argument updates the temporary value. If sendMessage fails, the parent should keep the failed message out of messages and show an error.
Putting the hooks together in one form
Use useActionState for durable results and validation messages. Use useFormStatus in a child component for the pending button. Use useOptimistic when an immediate visual response improves the experience.
Using Server Functions as form actions
A framework that supports React Server Functions can expose a server-side function directly as a form action:
// actions.js
"use server";
export async function createTodo(formData) {
const title = String(formData.get("title") ?? "").trim();
if (!title || title.length > 200) {
throw new Error("Invalid title");
}
// Check authorization, then save the todo.
}import { createTodo } from "./actions";
export function TodoForm() {
return (
<form action={createTodo}>
<input name="title" />
<button type="submit">Add</button>
</form>
);
}Forms that work before JavaScript loads
A Server Function form can submit through the server before the client bundle finishes loading. This is called progressive enhancement. The server still receives the form data, so the basic mutation does not depend entirely on hydration.
Treating Server Functions as public endpoints
A Server Function can be called by a modified client, not only by your rendered form. Validate every field on the server, enforce authorization, check ownership, limit input sizes, and avoid trusting hidden inputs. Return safe errors and keep secrets on the server.
Exercise
Why should a Server Function validate authorization even when its form is visible only to signed-in users?
Show answer
A client can call the function without using the visible form, so the server must enforce authorization at the trust boundary.