The idea in one paragraph
When the user drags a card, update the screen immediately, then send the request. If the server says no, put the screen back the way it was and tell the user why. The hard part is not the happy path. It is making the rollback reliable, and making sure the request is actually sent.
Step 1: make board state a pure reducer
Optimistic updates are much easier when every change is a plain action applied by a reducer, because the same function that moves a card on screen is easy to unit test. In TaskFlow the board state and actions look like this:
export interface BoardState {
phase: "loading" | "ready" | "error";
error: string | null;
tasks: Task[];
}
export type BoardAction =
| { type: "move"; id: number; status: TaskStatus; position: number }
| { type: "add_pending"; task: Task }
| { type: "add_confirmed"; tempId: number; task: Task }
| { type: "remove"; id: number }
/** Restore a snapshot taken before an optimistic update that the server rejected. */
| { type: "rollback"; tasks: Task[] };
Note the rollback action. It does not try to reverse the change; it simply puts a saved copy of the task list back. Reversing changes one by one is how rollback bugs are born.
Step 2: one helper for every optimistic call
Rather than repeat the try/catch in every handler, wrap it once. It takes a snapshot, dispatches the optimistic action, calls the server and restores the snapshot if anything throws:
async function optimistic<T>(action: BoardAction, call: () => Promise<T>, onOk?: (result: T) => void) {
const snapshot = stateRef.current.tasks;
setNotice(null);
dispatch(action);
try {
const result = await call();
onOk?.(result);
} catch (e) {
dispatch({ type: "rollback", tasks: snapshot });
setNotice(messageOf(e));
}
}
That one-line await call() on its own line is deliberate. My first version wrote onOk?.(await call()). When no callback was passed, optional chaining short-circuited and the server call never ran. The UI moved the card, nothing was saved, and no error appeared. A test caught it, which is a good argument for testing the failure and no-callback paths, not just the success path.
Step 3: temporary ids for new items
For creates, the item does not have a server id yet. Add it with a negative temporary id (add_pending), then swap it for the real record when the response arrives (add_confirmed). If the request fails, the same snapshot rollback removes it.
Step 4: make the failure visible
A silent rollback looks like a glitch. Show a notice with the server's message. The Laravel API returns one consistent error shape, so the front end can map every failure the same way:
// Laravel returns: { "message": "...", "code": "validation_failed", "errors": { "title": ["..."] } }
export class ApiError extends Error {
readonly status: number;
readonly code: string;
readonly fieldErrors: Record<string, string[]>;
}
Step 5: test the rollback
Because the server layer is behind an interface, a test can make the call fail on demand and assert the board returns to its original order. The demo of this project even has a "Simulate network failure" switch so you can watch the rollback happen.
Limits to be honest about
- Overlapping edits. A snapshot restores the whole list, so if two requests are in flight and the first fails, rolling back can undo the second change too. For heavy concurrent editing you need per-item versions or a queue.
- The server stays the source of truth. The optimistic state is a prediction. When a response arrives, prefer the server's record.
- Dialogs that close early. If the edit dialog closes before the server answers, field-level errors can only appear as a banner. That is a trade-off I documented in the repository.
When not to use it
Skip optimism for actions that are expensive to undo or that the user must see confirmed, such as payments. For moving a card, reordering a list or toggling a checkbox, it is exactly right.
The full code, including the Laravel API this talks to, is open source in the TaskFlow case study.
Original article written by Saad Ali Khan. Code samples are illustrative and free to adapt in your own projects.