Skip to content

Optimistic Updates

The Course
•
20 min study

With the last lesson's form, a new card appears only after the server answers. Most of the time, saving succeeds. Showing the card immediately, and quietly undoing it in the rare case it fails, makes the app feel instant. That's an optimistic update.

Cards that appear at once React · 5 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); // A pretend server. It takes a moment to answer, and refuses any card whose // title contains "fail", so you can see what happens when saving goes wrong. export async function saveCard(title, minutes) { await new Promise((resolve) => setTimeout(resolve, 600)); if (title.toLowerCase().includes("fail")) throw new Error("The server refused the card."); return { id: Date.now(), title, minutes, column: "todo" }; } import { useOptimistic, useState, startTransition } from "react"; import { saveCard } from "./api.js"; import { starterCards } from "./data.js"; export default function App() { const [cards, setCards] = useState(starterCards.slice(0, 2)); const [error, setError] = useState(null); const [optimisticCards, addOptimisticCard] = useOptimistic( cards, (current, title) => [...current, { id: `saving-${title}`, title, minutes: 15, saving: true }] ); async function addCard(formData) { const title = String(formData.get("title")).trim(); if (title === "") return; setError(null); addOptimisticCard(title); try { const card = await saveCard(title, 15); startTransition(() => setCards((current) => [...current, card])); } catch (err) { setError(`"${title}" wasn't saved: ${err.message}`); } } return ( <main> <h1>Study Board</h1> <form action={addCard} className="toolbar"> <input name="title" aria-label="Title" placeholder="Title" /> <button>Add</button> </form> {error && <p className="error">{error}</p>} <ul className="cards"> {optimisticCards.map((card) => ( <li key={card.id} className="card" style={card.saving ? { opacity: 0.6 } : undefined}> {card.title} {card.saving && <span className="muted">Saving…</span>} </li> ))} </ul> </main> ); } export const columns = [ { id: "todo", title: "To do" }, { id: "doing", title: "Doing" }, { id: "done", title: "Done" }, ]; export const starterCards = [ { id: 1, title: "Read about reducers", column: "todo", minutes: 20 }, { id: 2, title: "Draw the component tree", column: "doing", minutes: 15 }, { id: 3, title: "Practice useState", column: "done", minutes: 30 }, { id: 4, title: "Try context", column: "todo", minutes: 25 }, ]; body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Add Quick one: it appears straight away, faded, with Saving…, then turns solid. Add This will fail: it appears, then disappears, and an error explains why.

useOptimistic

JavaScript
const [optimisticCards, addOptimisticCard] = useOptimistic(
  cards,
  (current, title) => [...current, { id: `saving-${title}`, title, minutes: 15, saving: true }]
);
  • cards is the real state: what the server has confirmed.
  • optimisticCards is what to show. Normally it equals cards.
  • addOptimisticCard(title) runs the update function to add a temporary card, marked saving.

The optimistic version lasts only while the action is running. When the action finishes, optimisticCards goes back to following cards. If saving succeeded, cards now includes the real card, so it stays. If saving failed, nothing was added to cards, so the temporary card simply disappears. There's no rollback code to write.

Inside the action

JavaScript
async function addCard(formData) {
  const title = String(formData.get("title")).trim();
  if (title === "") return;
  setError(null);
  addOptimisticCard(title);
  try {
    const card = await saveCard(title, 15);
    startTransition(() => setCards((current) => [...current, card]));
  } catch (err) {
    setError(`"${title}" wasn't saved: ${err.message}`);
  }
}

addOptimisticCard must be called inside an action, here the form's. State updates after an await aren't part of the action any more, so the real update is wrapped in startTransition. That keeps it in step with the optimistic card disappearing. It uses an updater function, because other saves may have finished while this one was waiting.

When to be optimistic

Be optimistic when failure is rare, and undoing is easy to understand: adding a card, liking a post, ticking a checkbox. Don't be optimistic about payments, or anything where a wrongly shown success would mislead someone.

Exercise

Count what's saving

Add two cards quickly, one after the other. Above the list, show 2 saving while they're in flight, and nothing when none are.

Your working space React · 5 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); // A pretend server. It takes a moment to answer, and refuses any card whose // title contains "fail", so you can see what happens when saving goes wrong. export async function saveCard(title, minutes) { await new Promise((resolve) => setTimeout(resolve, 600)); if (title.toLowerCase().includes("fail")) throw new Error("The server refused the card."); return { id: Date.now(), title, minutes, column: "todo" }; } import { useOptimistic, useState, startTransition } from "react"; import { saveCard } from "./api.js"; import { starterCards } from "./data.js"; export default function App() { const [cards, setCards] = useState(starterCards.slice(0, 2)); const [error, setError] = useState(null); const [optimisticCards, addOptimisticCard] = useOptimistic( cards, (current, title) => [...current, { id: `saving-${title}`, title, minutes: 15, saving: true }] ); async function addCard(formData) { const title = String(formData.get("title")).trim(); if (title === "") return; setError(null); addOptimisticCard(title); try { const card = await saveCard(title, 15); startTransition(() => setCards((current) => [...current, card])); } catch (err) { setError(`"${title}" wasn't saved: ${err.message}`); } } return ( <main> <h1>Study Board</h1> <form action={addCard} className="toolbar"> <input name="title" aria-label="Title" placeholder="Title" /> <button>Add</button> </form> {error && <p className="error">{error}</p>} <ul className="cards"> {optimisticCards.map((card) => ( <li key={card.id} className="card" style={card.saving ? { opacity: 0.6 } : undefined}> {card.title} {card.saving && <span className="muted">Saving…</span>} </li> ))} </ul> </main> ); } export const columns = [ { id: "todo", title: "To do" }, { id: "doing", title: "Doing" }, { id: "done", title: "Done" }, ]; export const starterCards = [ { id: 1, title: "Read about reducers", column: "todo", minutes: 20 }, { id: 2, title: "Draw the component tree", column: "doing", minutes: 15 }, { id: 3, title: "Practice useState", column: "done", minutes: 30 }, { id: 4, title: "Try context", column: "todo", minutes: 25 }, ]; body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea

Separate confirmed data from temporary display data. The saving indicator belongs to the temporary layer.

Hint 2: a first step

The saving cards are the ones in optimisticCards marked saving: a derived value.

Show one solution
JavaScript
const savingCount = optimisticCards.filter((card) => card.saving).length;
JSX
{savingCount > 0 && <p className="muted">{savingCount} saving</p>}

Was this article helpful?

Your response is saved on this device.