React · Lesson 77 of 120
useOptimistic
Instant feedback.
Waiting for the server makes apps feel slow. Optimistic updates show the change straight away, assuming it will work, then confirm or undo it when the server answers.
- Waiting feels slow
- Show it now
- Confirm later
Posting a review
Use optimistic shows a change straight away, before the server confirms it. Here a review appears instantly, marked as sending. When saving finishes, the real list replaces the optimistic one. If saving failed, the optimistic item would simply disappear. We post a review. Run it.
App.jsxjsx
import { useState, useOptimistic, startTransition } from "react";
const save = text => new Promise(r => setTimeout(() => r(text), 1000));
export default function App() {
const [reviews, setReviews] = useState(["Great bike"]);
const [shown, addOptimistic] = useOptimistic(reviews, (list, text) => [...list, text + " (sending...)"]);
function post(text) {
startTransition(async () => {
addOptimistic(text);
const saved = await save(text);
startTransition(() => setReviews(r => [...r, saved]));
});
}
return (<div>
<ul>{shown.map(r => <li key={r}>{r}</li>)}</ul>
<button id="post" onClick={() => post("Love the lights")}>Post review</button>
</div>);
}Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}Also uses actions.json
[{"click": "#post"}, {"wait": 300}]Summary
Use optimistic shows changes instantly, and falls back if they fail. Next, the use hook.
Key takeaways- useOptimistic
- Instant
- Confirmed later
Next up: The use Hook — promises and context