A save that takes a second feels broken if nothing changes on screen. Showing
the new item at once, before the server confirms it, is an optimistic
update. It's a promise that work is in progress, not proof that it's done, so
the confirmed list stays the source of truth and the temporary view is derived
from it while the action runs.
Read, predict, run
lib/contract.js holds the merge rule: the saved rows plus one pending row,
marked saving, without changing the saved array:
ItemList.jsx uses it with React's useOptimistic. The hook takes the
confirmed items from the server and a function that combines them with
whatever you pass to addPending. While the action runs, shown is the
combined list; when the action finishes, React throws the optimistic view away
and shown is simply items again, which by then the server may have
refreshed:
The action addItem takes 800 ms and, to make failure easy to try, refuses any
title containing fail. Run the lab and add Forms, then Please fail.
Predict what the list shows during and after each save.
Optimistic Data Is a Temporary ViewNext.js · 8 filesimport "./globals.css";
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<header>
<strong>Study Library · Practice lab</strong>
</header>
{children}
</body>
</html>
);
}
import Cases from "./Cases.jsx";
import ItemList from "./ItemList.jsx";
import { listItems } from "@/lib/items.js";
export default async function Page() {
const items = await listItems();
return (
<main>
<h1>Optimistic Data Is a Temporary View</h1>
<ItemList items={items} />
<Cases />
</main>
);
}
"use server";
import { revalidatePath } from "next/cache";
import { insertItem } from "@/lib/items.js";
export async function addItem(previous, formData) {
const title = String(formData.get("title") ?? "").trim();
// A slow save, so the optimistic row is visible for a while.
await new Promise((resolve) => setTimeout(resolve, 800));
// Pretend the database refuses any title containing "fail".
if (title.toLowerCase().includes("fail"))
return { error: `The library couldn't save “${title}”.` };
await insertItem(title);
revalidatePath("/");
return { error: null };
}
import { run, examples } from "@/lib/contract.js";
const text = (value) => JSON.stringify(value) ?? "undefined";
export default async function Cases() {
const results = await Promise.all(
examples.map(async ([input, expected]) => {
// Record the input before running, to show whether run changed it.
const before = text(input);
const actual = await run(input);
return {
input: before,
expected,
actual,
kept: text(input) === before,
pass: text(actual) === text(expected),
};
}),
);
return (
<section>
<h2>Executable cases</h2>
<p>
Checks: {results.filter((row) => row.pass).length}/{results.length}{" "}
passed
</p>
<table>
<thead>
<tr>
<th>Input</th>
<th>Expected</th>
<th>Actual</th>
<th>Input kept</th>
</tr>
</thead>
<tbody>
{results.map((row, i) => (
<tr key={i}>
<td>
<code>{row.input}</code>
</td>
<td>
<code>{text(row.expected)}</code>
</td>
<td className={row.pass ? "pass" : "fail"}>
<code>{text(row.actual)}</code>
</td>
<td className={row.kept ? "pass" : "fail"}>
{row.kept ? "yes" : "no: run changed it"}
</td>
</tr>
))}
</tbody>
</table>
</section>
);
}
"use client";
import { useActionState, useOptimistic } from "react";
import { addItem } from "./actions.js";
import { run } from "@/lib/contract.js";
export default function ItemList({ items }) {
// While an action is running, show the saved items plus the pending one.
// When it ends, React drops the optimistic view and shows `items` again.
const [shown, addPending] = useOptimistic(items, (saved, pending) =>
run({ saved, pending }),
);
const [state, formAction, isPending] = useActionState(
async (previous, formData) => {
addPending({ id: "pending", title: String(formData.get("title")) });
return addItem(previous, formData);
},
{ error: null },
);
return (
<section>
<ul>
{shown.map((item) => (
<li key={item.id}>
{item.title}
{item.saving && " (saving…)"}
</li>
))}
</ul>
<form action={formAction}>
<label>
Title <input name="title" />
</label>
<button disabled={isPending}>Add</button>
</form>
<p role="alert">{state.error}</p>
</section>
);
}
body {
font: 16px/1.5 system-ui;
margin: 0;
color: #182b3c;
background: #f4f8fc;
}
header,
main {
max-width: 900px;
margin: auto;
padding: 20px;
}
header {
border-bottom: 1px solid #cbd5e1;
}
a {
color: #075985;
}
button,
input,
textarea,
select {
font: inherit;
padding: 8px;
margin: 4px;
}
button {
cursor: pointer;
}
table {
border-collapse: collapse;
width: 100%;
}
th,
td {
padding: 10px;
border: 1px solid #cbd5e1;
text-align: left;
vertical-align: top;
}
pre,
code {
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.pass {
color: #166534;
}
.fail,
[role="alert"] {
color: #a01818;
}
section {
margin: 16px 0;
padding: 12px;
background: white;
border-radius: 8px;
}
nav {
display: flex;
gap: 16px;
}
export function run({ saved, pending }) {
return pending ? [...saved, { ...pending, saving: true }] : saved;
}
export const examples = [
[
{ saved: [], pending: { id: "temp", title: "Forms" } },
[{ id: "temp", title: "Forms", saving: true }],
],
];
// A pretend table in server memory.
const items = [{ id: 1, title: "Routing" }];
export async function listItems() {
return items.map((item) => ({ ...item }));
}
export async function insertItem(title) {
items.push({ id: items.length + 1, title });
}
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Check your prediction
Forms appears at once as Forms (saving…). After 800 ms the action
saves it and calls revalidatePath, the page sends a new items, and the
row shows as plain Forms.
Please fail (saving…) appears at once too. After 800 ms the action
returns an error instead. The optimistic view ends, items never contained
the row, so it disappears, and The library couldn't save “Please fail”.
shows under the form.
Nothing had to undo the failed row by hand: it was never added to the real
list.
The failure to avoid
Counting temporary rows as saved records lies about durability. On a failed action the temporary view must disappear and the error must remain discoverable.
Trace {"saved": [], "pending": null}, then the lab's failed Please fail
save. Where does the temporary row go each time?
Exercise
Extend the contract
Do not append a pending row if the confirmed list already contains its id.
Edit lib/contract.js, then rerun the original cases. If the requested rule
changes an earlier result, update that expected value deliberately. Keep the
other cases. Add the acceptance cases to examples so the preview checks them too.
Your working spaceNext.js · 8 filesimport "./globals.css";
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<header>
<strong>Study Library · Practice lab</strong>
</header>
{children}
</body>
</html>
);
}
import Cases from "./Cases.jsx";
import ItemList from "./ItemList.jsx";
import { listItems } from "@/lib/items.js";
export default async function Page() {
const items = await listItems();
return (
<main>
<h1>Optimistic Data Is a Temporary View</h1>
<ItemList items={items} />
<Cases />
</main>
);
}
"use server";
import { revalidatePath } from "next/cache";
import { insertItem } from "@/lib/items.js";
export async function addItem(previous, formData) {
const title = String(formData.get("title") ?? "").trim();
// A slow save, so the optimistic row is visible for a while.
await new Promise((resolve) => setTimeout(resolve, 800));
// Pretend the database refuses any title containing "fail".
if (title.toLowerCase().includes("fail"))
return { error: `The library couldn't save “${title}”.` };
await insertItem(title);
revalidatePath("/");
return { error: null };
}
import { run, examples } from "@/lib/contract.js";
const text = (value) => JSON.stringify(value) ?? "undefined";
export default async function Cases() {
const results = await Promise.all(
examples.map(async ([input, expected]) => {
// Record the input before running, to show whether run changed it.
const before = text(input);
const actual = await run(input);
return {
input: before,
expected,
actual,
kept: text(input) === before,
pass: text(actual) === text(expected),
};
}),
);
return (
<section>
<h2>Executable cases</h2>
<p>
Checks: {results.filter((row) => row.pass).length}/{results.length}{" "}
passed
</p>
<table>
<thead>
<tr>
<th>Input</th>
<th>Expected</th>
<th>Actual</th>
<th>Input kept</th>
</tr>
</thead>
<tbody>
{results.map((row, i) => (
<tr key={i}>
<td>
<code>{row.input}</code>
</td>
<td>
<code>{text(row.expected)}</code>
</td>
<td className={row.pass ? "pass" : "fail"}>
<code>{text(row.actual)}</code>
</td>
<td className={row.kept ? "pass" : "fail"}>
{row.kept ? "yes" : "no: run changed it"}
</td>
</tr>
))}
</tbody>
</table>
</section>
);
}
"use client";
import { useActionState, useOptimistic } from "react";
import { addItem } from "./actions.js";
import { run } from "@/lib/contract.js";
export default function ItemList({ items }) {
// While an action is running, show the saved items plus the pending one.
// When it ends, React drops the optimistic view and shows `items` again.
const [shown, addPending] = useOptimistic(items, (saved, pending) =>
run({ saved, pending }),
);
const [state, formAction, isPending] = useActionState(
async (previous, formData) => {
addPending({ id: "pending", title: String(formData.get("title")) });
return addItem(previous, formData);
},
{ error: null },
);
return (
<section>
<ul>
{shown.map((item) => (
<li key={item.id}>
{item.title}
{item.saving && " (saving…)"}
</li>
))}
</ul>
<form action={formAction}>
<label>
Title <input name="title" />
</label>
<button disabled={isPending}>Add</button>
</form>
<p role="alert">{state.error}</p>
</section>
);
}
body {
font: 16px/1.5 system-ui;
margin: 0;
color: #182b3c;
background: #f4f8fc;
}
header,
main {
max-width: 900px;
margin: auto;
padding: 20px;
}
header {
border-bottom: 1px solid #cbd5e1;
}
a {
color: #075985;
}
button,
input,
textarea,
select {
font: inherit;
padding: 8px;
margin: 4px;
}
button {
cursor: pointer;
}
table {
border-collapse: collapse;
width: 100%;
}
th,
td {
padding: 10px;
border: 1px solid #cbd5e1;
text-align: left;
vertical-align: top;
}
pre,
code {
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.pass {
color: #166534;
}
.fail,
[role="alert"] {
color: #a01818;
}
section {
margin: 16px 0;
padding: 12px;
background: white;
border-radius: 8px;
}
nav {
display: flex;
gap: 16px;
}
export function run({ saved, pending }) {
return pending ? [...saved, { ...pending, saving: true }] : saved;
}
export const examples = [
[
{ saved: [], pending: { id: "temp", title: "Forms" } },
[{ id: "temp", title: "Forms", saving: true }],
],
];
// A pretend table in server memory.
const items = [{ id: 1, title: "Routing" }];
export async function listItems() {
return items.map((item) => ({ ...item }));
}
export async function insertItem(title) {
items.push({ id: items.length + 1, title });
}
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea
A pending row stands in for a row that isn't saved yet. Once the confirmed list
has a row with the same id, the stand-in has nothing left to stand in for.
Hint 2: a first step
Check identity before merging; a completed response must not leave a duplicate row.
Show one solution
Replace the exported run function and any constants shown here; keep the
examples export underneath it. Compare the result with your own approach.
Checking the saved rows for the pending id before merging means a confirmed
row and its pending twin never show together. That needs the client to choose
the id, for example with crypto.randomUUID(), and the server to keep it. The
lab's "pending" id never matches a saved row, which is why it relies on the
refreshed list replacing the view when the action ends.
Explain it without the code
Write what the reader should see if the save fails halfway, and which part of
the code guarantees it.
Going further
Read the Next.js guide for the framework boundary around this rule.
The preview runs code-playpad's Next.js simulation. Real caching, hydration,
authentication and persistence require the real-server checks described on Day 7.
Completion is saved in this browser only. It does not measure mastery.