useOptimistic with Server Actions
What you'll learn: How to combine useOptimistic with server actions to create forms that feel instant, even when the network is slow.
The Power of Combining Patterns
You've learned useOptimistic for instant UI updates and server actions for progressive enhancement. Now we bring them together: when a user submits a form, show the expected result immediately while the server processes the real request in the background.
The Complete Pattern
import { useOptimistic } from 'react';
import { useActionState } from 'react';
function CommentList({ comments }) {
const [optimisticComments, addOptimisticComment] = useOptimistic(
comments,
(state, newComment) => [...state, newComment]
);
async function submitComment(prevState, formData) {
const text = formData.get('comment');
const tempComment = { id: crypto.randomUUID(), text, pending: true };
// Show optimistically
addOptimisticComment(tempComment);
// Actual server work
const result = await saveCommentToServer(text);
return result;
}
const [state, formAction, isPending] = useActionState(submitComment, null);
return (
<>
<ul>
{optimisticComments.map(comment => (
<li key={comment.id} style={{ opacity: comment.pending ? 0.5 : 1 }}>
{comment.text}
</li>
))}
</ul>
<form action={formAction}>
<input name="comment" />
<button disabled={isPending}>Post</button>
</form>
</>
);
}
How It Works
When the form submits, addOptimisticComment immediately adds the new comment to the UI—faded to show it's pending. The server action runs in parallel. When complete, React replaces the optimistic state with real server data. If the server fails, the optimistic update automatically rolls back via your error boundary.
This pattern makes slow networks feel fast because users see their action succeed instantly, not after a 2-second wait.
Key Takeaway: Pairing useOptimistic with server actions creates the illusion of zero-latency interactions—your UI updates instantly while the server catches up behind the scenes.