Menu

Pending States and Optimistic UI

Lesson 3: Pending States and Optimistic UI

How do you give instant feedback?

Hook From What it does Example
useActionState react Holds action result and isPending Form errors
useFormStatus react-dom Tells a child of a form whether it is submitting Reusable submit button
useOptimistic react Shows an expected result before the server confirms Like counts, new comments
useTransition react Marks a non-form update as pending Button that calls an action

Example: reusable submit button

'use client';
import { useFormStatus } from 'react-dom';

export function SubmitButton({ label }: { label: string }) {
  const { pending } = useFormStatus();
  return (
    <button type="submit" disabled={pending}>
      {pending ? 'Saving…' : label}
    </button>
  );
}

Example: optimistic bookmark

'use client';
import { useOptimistic, startTransition } from 'react';
import { toggleBookmark } from './actions';

export function BookmarkButton({ courseId, saved }: { courseId: string; saved: boolean }) {
  const [optimisticSaved, setOptimisticSaved] = useOptimistic(saved);

  function handleClick() {
    startTransition(async () => {
      setOptimisticSaved(!optimisticSaved); // UI updates now
      await toggleBookmark(courseId);       // Server confirms later
    });
  }

  return <button onClick={handleClick}>{optimisticSaved ? '★ Saved' : '☆ Save'}</button>;
}

How it works

  • useFormStatus must be used in a component inside the <form>, not in the component that renders the form.
  • useOptimistic shows a temporary value during the transition. When the action finishes and fresh data arrives, React replaces it with the real value.
  • If the action fails, the optimistic value is discarded and the UI returns to the real state automatically.

Common mistakes

Mistake Effect Fix
Calling useFormStatus in the form's own component pending is always false Move the button into a child component
Optimistic updates for risky actions (payments) Users see success that did not happen Use optimistic UI only for low-risk, reversible actions
No error message when an optimistic update fails Silent rollback confuses users Show a toast or message on failure

Key takeaways

  • Disable buttons and show progress text while actions run.
  • Use optimistic UI for quick, reversible actions to make the app feel instant.

Try it: Add a bookmark button to each course card that updates instantly with useOptimistic.


Nextjs Tutorial

J

Jebasta





Get in Touch For Details