Q31: How do you pair useOptimistic with Server Actions for instant UI responses?

To eliminate visual network delays, call useOptimistic inside client forms. When a user submits a form, the client state updates immediately with expected values. If the background Server Action succeeds, server state syncs; if it fails, UI state rolls back.

Optimistic UI Comment Form
'use client';
import { useOptimistic } from 'react';
import { addCommentAction } from './actions';

export function CommentList({ comments }) {
  const [optimisticComments, addOptimistic] = useOptimistic(
    comments,
    (state, newText) => [...state, { text: newText, pending: true }]
  );

  const handleAction = async (formData) => {
    const text = formData.get('comment');
    addOptimistic(text); // Instant UI update
    await addCommentAction(formData); // Server write
  };

  return (
    <form action={handleAction}>
      <input name="comment" />
      {optimisticComments.map((c, i) => <p key={i}>{c.text}</p>)}
    </form>
  );
}
💡 addOptimistic immediately appends comment text to UI before addCommentAction finishes on server.
Key Takeaways
  • Provides zero perceived UI latency during Server Action mutations.
  • Automatically reverts optimistic state updates if the server request fails.
Knowledge Check

What happens if a Server Action fails after useOptimistic has updated the client UI?