Next.js Optimistic Updates
An optimistic update shows the new book at once, before the server answers. The list feels instant.
The list with the new book added early
The hook keeps the list and adds the new book to it. The page shows that list.
const [optimisticBooks, addOptimisticBook] = useOptimistic(
books,
(current: Book[], newBook: Book) => [...current, newBook]
);The submit adds, then saves
The submit adds the stand-in book first, then calls the action. The save follows.
async function submit(formData: FormData) {
const title = String(formData.get("title") ?? "");
const author = String(formData.get("author") ?? "");
addOptimisticBook({
id: "temp-" + Date.now(),
title,
author,
read: false,
});
formAction(formData);
}Example
node -e 'const books = ["Dune", "The Hobbit", "Pride and Prejudice"]; const optimistic = [...books, "The Left Hand of Darkness"]; console.log("Shown at once:", optimistic.length); console.log(optimistic.join(", "));'Key points
- Optimistic: showing the result before the server confirms it
- useOptimistic: the hook that holds the list with the new book added early
- The new book gets a stand-in id, temp plus the time. The real id comes later.
- The form still calls the action. The server save runs as before.
- If the server says no, the stand-in book disappears. The list goes back to the truth.
In this example, the script builds the optimistic list. Three saved books plus the new one make four shown at once. The new book shows before the server answers, so the reader sees it right away. When the server confirms the save, the stand-in id is swapped for the real one. When the server says no, the fourth book drops out, and the list is back to three.
Note
The instant show and the rollback are browser-visible. Curl shows the list and the form, not the swap.
Try it Yourself
Edit the code, then press Run.
Running is simulated · TypeScript Playground
Exercise
What does the optimistic update show first?