Skip to content
ClapelloNotes by Barath
ReactCh 16 · 3/6
Core4 min readUpdated

React / 90

useOptimistic: instant UI that rolls back

TL;DR

Show the result of an action before the server confirms it. If the action fails, React drops the guess and shows the real state again, with no undo code.

A temporary copy of your state

const [optimisticValue, setOptimistic] = useOptimistic(value, reducer);
  • value: your real state (from useState, props or useActionState).
  • reducer(current, input) (optional): how a guess changes the value, like (likes, amount) => likes + amount. Without it, whatever you pass to setOptimistic becomes the value.
  • optimisticValue: equals value whenever no Action is running. While one is, it's the guessed version.

server says OK

before

♡ 12

click

♥ 13

saved

♥ 13

server fails

before

♡ 12

click

♥ 13

rolled back

♡ 12

Highlighted = the optimistic guess, shown instantly while the request is in flight.

The optimistic value only lives while the Action runs. When it ends, React shows the real state again: updated if the save worked, unchanged (a rollback) if it failed.

A like button

LikeButton.jsx
import { startTransition, useOptimistic, useState } from "react";
import { saveLike } from "./api.js";
 
export default function LikeButton({ initialLikes }) {
  const [likes, setLikes] = useState(initialLikes);
  const [optimisticLikes, addLike] = useOptimistic(likes, (current, amount) => current + amount);
  const [error, setError] = useState(null);
 
  function handleLike() {
    setError(null);
    startTransition(async () => {
      addLike(1); // shows instantly
      try {
        const saved = await saveLike(); // the server's real count
        startTransition(() => setLikes(saved)); // ink it in
      } catch {
        startTransition(() => setError("Couldn't like. Try again."));
      }
    });
  }
 
  return (
    <>
      <button onClick={handleLike}>♥ {optimisticLikes}</button>
      {error && <p role="alert">{error}</p>}
    </>
  );
}

Render optimisticLikes, never likes, in the UI. On success, the real state and the optimistic value meet in the same render, so there's no flicker. On failure, nothing touched likes, so the count drops back on its own. You only add the error message.

An optimistic like

Try it

on screen (optimistic)

♡ 12

real state (post)

♡ 12

Tap the heart: it changes instantly. With failure on, it snaps back after 1.5 s because the real state never changed.

A chat message that says "Sending…"

Inside a form action you're already in an Action, so there's no startTransition around the optimistic call. The reducer adds a temporary message marked sending:

Chat.jsx
const [optimisticMessages, addOptimistic] = useOptimistic(
  messages,
  (current, text) => [...current, { id: crypto.randomUUID(), text, sending: true }]
);
 
async function sendAction(formData) {
  const text = formData.get("message");
  addOptimistic(text);
  const saved = await sendMessage(text);
  startTransition(() => setMessages((m) => [...m, saved]));
}
 
return (
  <>
    {optimisticMessages.map((m) => (
      <p key={m.id}>{m.text} {m.sending && <small>Sending…</small>}</p>
    ))}
    <form action={sendAction}>
      <input name="message" />
    </form>
  </>
);

Gotchas

Recall

Can you answer these?

0/4

Answer out loud (or in your head) before you tap. That's what makes it stick.

Saved on this device only. No login.