React useOptimistic Hook: How It Works, With Examples

Muhaymin Bin Mehmood

Muhaymin Bin Mehmood

·
7 min read
Published Mar 6, 2024
Updated Oct 9, 2026
What is useOptimistic Hook in React 19 and How Can it Enhance User Experience banner image
11 min read
1,112 words
16 sections8 code blocks

useOptimistic is a React 19 hook that shows the result of an action before the server confirms it, like a like count going up the moment you click, or a chat message appearing while it's still sending. When the action finishes, React swaps the optimistic value for the real state. If the request fails, the optimistic value disappears on its own, so you don't write rollback code.

Tested with: React 19.3 in StrictMode, in Chromium 156 and WebKit 27.2 (Safari's engine) via Playwright, against a fake API with a 300 ms delay that we could switch to failing. October 2026.

useOptimistic Syntax

JavaScript
const [optimisticState, addOptimistic] = useOptimistic(state, updateFn);

// updateFn is optional and works like a reducer:
// (currentState, optimisticValue) => nextOptimisticState
  • state: the real value, usually from useState, props or server data. It's what you see when no action is running.
  • updateFn(currentState, optimisticValue): returns the value to show while an action is pending. Leave it out and the second item simply sets the optimistic value.
  • optimisticState: render this instead of state.
  • addOptimistic(value): call it inside an Action, meaning a function passed to startTransition or to <form action>. Called anywhere else, React logs an error and nothing useful happens (see Common Mistakes).

It is part of stable React since React 19 (December 2024). It doesn't exist in React 18. See the official useOptimistic reference for the full API.

Example 1: An Optimistic Like Button

First, two small API helpers built on fetch(). Both throw when the server answers with an error, which is what makes the rollback work:

JavaScript
// api.js — replace with your real requests
export async function saveLike() {
  const res = await fetch("/api/like", { method: "POST" });
  if (!res.ok) throw new Error(`Like failed: ${res.status}`);
  const { likes } = await res.json();
  return likes; // the real count from the server
}

export async function sendMessage(text) {
  const res = await fetch("/api/messages", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ text }),
  });
  if (!res.ok) throw new Error(`Send failed: ${res.status}`);
  return res.json(); // { id, text }
}

The button shows the new count immediately, then shows the server's number once it arrives:

JSX
import { useOptimistic, useState, useTransition } from "react";
import { saveLike } from "./api.js";

export function LikeButton({ initialLikes }) {
  const [likes, setLikes] = useState(initialLikes);
  const [optimisticLikes, addOptimisticLike] = useOptimistic(
    likes,
    (current, amount) => current + amount
  );
  const [isPending, startTransition] = useTransition();
  const [error, setError] = useState(null);

  function handleClick() {
    setError(null);
    startTransition(async () => {
      addOptimisticLike(1); // shows the new count right away
      try {
        const saved = await saveLike(); // the server's real count
        startTransition(() => setLikes(saved));
      } catch {
        // No rollback code needed: when this action ends,
        // optimisticLikes goes back to `likes` on its own.
        setError("Couldn't save your like. Please try again.");
      }
    });
  }

  return (
    <div>
      <button onClick={handleClick}>♥ {optimisticLikes}</button>
      {isPending && <small> Saving…</small>}
      {error && <p role="alert">{error}</p>}
    </div>
  );
}

What happened in our tests (Chromium and WebKit gave identical results):

ScenarioRight after the clickAfter the server answers
Request succeeds♥ 11 Saving…♥ 11
Request fails♥ 12 Saving…♥ 11 and the error message
Three quick clicks♥ 14 Saving…♥ 14 (the server's count)
  • The rollback is automatic. On failure we never set the count back; optimisticLikes returned to likes when the action ended.
  • Use the updateFn for counters. (current, amount) => current + amount builds on the current optimistic value, so three fast clicks showed +3. Setting likes + 1 directly would read the same stale likes every time.
  • Wrap the update after await in startTransition. The React docs ask for this, because code after an await is no longer inside the original transition.

The setter form, for when you don't need an updateFn:

JavaScript
// Without updateFn, the second value just sets the optimistic state:
const [optimisticLikes, setOptimisticLikes] = useOptimistic(likes);

startTransition(async () => {
  setOptimisticLikes(likes + 1);
  // ...
});

Example 2: Optimistic Messages With a Form Action

With <form action={fn}>, React runs fn as an Action, so you can call addOptimistic directly. Here the new message appears with a "sending…" label until the server returns it:

JSX
import { startTransition, useOptimistic, useState } from "react";
import { sendMessage } from "./api.js";

export function Chat() {
  const [messages, setMessages] = useState([]);
  const [error, setError] = useState(null);
  const [optimisticMessages, addOptimisticMessage] = useOptimistic(
    messages,
    (current, text) => [
      ...current,
      { id: `temp-${current.length}`, text, sending: true },
    ]
  );

  // A function passed to <form action> already runs as an Action,
  // so no startTransition is needed around the optimistic update.
  async function formAction(formData) {
    const text = formData.get("message");
    setError(null);
    addOptimisticMessage(text);
    try {
      const saved = await sendMessage(text); // { id, text }
      startTransition(() => setMessages((list) => [...list, saved]));
    } catch {
      setError(`"${text}" wasn't sent. Please try again.`);
    }
  }

  return (
    <div>
      <ul>
        {optimisticMessages.map((message) => (
          <li key={message.id}>
            {message.text}
            {message.sending && <small> (sending…)</small>}
          </li>
        ))}
      </ul>
      {error && <p role="alert">{error}</p>}
      <form action={formAction}>
        <input name="message" required />
        <button type="submit">Send</button>
      </form>
    </div>
  );
}

In our tests:

  • Right after submit, the list showed hi (sending…); 300 ms later it showed hi (the server's copy), still one item, not two.
  • The input kept its text while sending and was cleared after the action finished. React 19 resets an uncontrolled form after its action completes, so we didn't call reset().
  • When the server failed, oops (sending…) appeared, then disappeared and the error message showed. The earlier hi stayed.

The temporary id matters: React needs a key for the pending item. When the real message arrives with the server's id, the temporary one is gone because the optimistic list is rebuilt from messages.

How useOptimistic Works

  • While at least one Action is pending, React renders updateFn(state, value) for each optimistic value you added, in order.
  • When every pending Action has finished, the optimistic values are dropped and optimisticState equals state again.
  • So the final screen is always whatever you put in real state. Success: you updated state with the server's data. Failure: you didn't, so the old value comes back.

This is why there is no "revert" call. It's also why you must update the real state on success: if you forget, the optimistic value vanishes when the action ends and the UI goes back to the old value.

Common Mistakes

Calling it outside an Action

JSX
import { useOptimistic, useState } from "react";
import { saveLike } from "./api.js";

// ❌ Don't do this: the optimistic update is not inside an Action
export function WrongLikeButton({ initialLikes }) {
  const [likes, setLikes] = useState(initialLikes);
  const [optimisticLikes, setOptimisticLikes] = useOptimistic(likes);

  async function handleClick() {
    setOptimisticLikes(likes + 1);
    setLikes(await saveLike());
  }

  return <button onClick={handleClick}>♥ {optimisticLikes}</button>;
}

In both browsers React logged:

Bash
An optimistic state update occurred outside a transition or action. To fix, move the update to an action, or wrap with startTransition.

And the optimistic value was useless: in Chromium the button stayed at ♥ 10 until the server answered; in WebKit ♥ 11 flashed for a few milliseconds and went back to ♥ 10. Fix: move the call into startTransition(async () => { … }) or a form action, as in the examples above.

MistakeWhat happensFix
addOptimistic outside startTransition or a form actionConsole error; no optimistic UICall it inside an Action
Not updating real state on successUI jumps back to the old value when the action endsstartTransition(() => setState(serverData))
Not throwing on HTTP errorsfetch() resolves on 404/500, so nothing rolls back and no error showsif (!res.ok) throw new Error(…)
Setting likes + 1 instead of using updateFnFast repeated clicks show +1, not +3useOptimistic(likes, (c, n) => c + n)
Rendering state instead of optimisticStateThe UI never changes earlyRender the first value useOptimistic returns
Using it in React 18useOptimistic is not a functionUpgrade to React 19

useOptimistic vs useState

You can build the same like button with useState, but the rollback is your job:

JavaScript
// The same like button with useState only: you write the rollback yourself
const [likes, setLikes] = useState(initialLikes);

async function handleClick() {
  const previous = likes;
  setLikes(previous + 1);
  try {
    setLikes(await saveLike());
  } catch {
    setLikes(previous); // undo by hand
  }
}
useOptimisticuseState only
Rollback on errorAutomaticManual (save and restore the old value)
Multiple requests in flightEach pending value is applied in order, then droppedEasy to restore the wrong "previous" value
Pending statePairs with useTransition / form actionsTrack isLoading yourself
NeedsReact 19 and ActionsAny React version

If you already use a data library such as TanStack Query or SWR, their own optimistic-update features work too; useOptimistic is the built-in option when you use Actions. For broader state patterns, see our React state management guide.

When Not to Be Optimistic

  • Payments, deletions you can't undo, or anything where showing success and then failing would mislead the user.
  • Actions that usually fail validation on the server (for example, a username that may be taken).
  • Results only the server can compute, like a generated ID shown to the user or a calculated total.

Optimistic UI fits small, frequent, usually successful actions: likes, follows, toggles, adding items to a list, sending messages.

FAQs

What does useOptimistic do in React?

It returns a copy of your state that you can change temporarily while an async Action is running. React shows that copy until the Action finishes, then goes back to the real state.

How do I roll back an optimistic update when the request fails?

You don't have to. If the Action ends without updating the real state, the optimistic value is dropped automatically. Just make sure your request throws on errors and show a message in catch.

Why do I get "An optimistic state update occurred outside a transition or action"?

You called the setter from a normal event handler. Wrap the call in startTransition(async () => { … }) (from useTransition or imported from React), or call it inside a function passed to <form action>.

What's the difference between useOptimistic and useState?

useState holds the real value. useOptimistic wraps a real value and lets you show a temporary one during an Action, with automatic rollback. You usually use both together.

Is useOptimistic still experimental?

No. It shipped in stable React 19 in December 2024. It was experimental (Canary only) before that, which is why some older articles say so. See what else changed in our React 19 overview and our guide to the use() hook.

Does useOptimistic work with Next.js Server Actions?

Yes. A Server Action passed to <form action> or called inside startTransition is an Action like any other, so the patterns above work in Client Components. The hook itself must run in a Client Component ("use client").

Does it run twice in development?

StrictMode renders components twice in development, and our tests ran under StrictMode with the expected results. If your effects run twice, see why useEffect runs twice.

No comments yet. Be the first to comment!

Leave a Comment

2000 characters remaining

Related Articles

View all
Muhaymin Bin Mehmood

About Muhaymin Bin Mehmood

Front-end Developer skilled in the MERN stack, experienced in web and mobile development. Proficient in React.js, Node.js, and Express.js, with a focus on client interactions, sales support, and high-performance applications.