Rollback optimistic updates
Display a temporary prediction while saving
useOptimistic(base, reducer) provides a temporary view during an Action. The pure reducer receives the current base or optimistic value and an update input. The base is still the source of truth when the Action settles. Optimism is suitable for reversible, low-risk changes with a clear recovery message; avoid presenting a financial transfer or irreversible operation as confirmed before the server confirms it.
import React,{useState,useTransition,startTransition,useActionState,useOptimistic} from 'react';import {useFormStatus} from 'react-dom';const delay=()=>new Promise(resolve=>setTimeout(resolve,600));export default function App(){const [label,setLabel]=useState('Unassigned');const [view,show]=useOptimistic(label);const [pending,run]=useTransition(); function update(){run(async()=>{show('Lamp');await delay();startTransition(()=>setLabel('Lamp – checked'));});} return <section><p role="status">{view}{pending?' (saving)':''}</p><button disabled={pending} onClick={update}>Assign lamp</button></section>;}The predicted Lamp appears during the Action. After the mock response, the authoritative label is Lamp – checked, so the final UI uses that value instead of retaining the prediction. Optimistic setters should run in an Action or Transition, not as ordinary permanent state updates. If base state changes while an optimistic reducer is pending, React can recalculate the view using the updated base.
Roll back a rejected optimistic addition
import React,{useState,useTransition,startTransition,useActionState,useOptimistic} from 'react';import {useFormStatus} from 'react-dom';const delay=()=>new Promise(resolve=>setTimeout(resolve,600));function parseLabel(data){ const value=data.get('label'); if(typeof value!=='string') return {error:'Enter a repair label.'}; const label=value.trim(); if(!label||label.length>40) return {error:'Use 1–40 characters.'}; return {label};}async function saveRepair(label, fail=false){ if(fail) return {error:'Repair queue unavailable. Try again.'}; return {label:label.trim().replace(/ +/g,' ')};}function addPending(items,item){return [...items.filter(x=>x.id!==item.id),{...item,pending:true}];}function confirmRepair(items,item){return [...items.filter(x=>x.id!==item.id),{id:item.id,label:item.label}];}function Submit(){const {pending}=useFormStatus();return <button disabled={pending} type="submit">{pending?'Saving…':'Add repair'}</button>;}export default function App(){const [items,setItems]=useState([]);const [view,add]=useOptimistic(items,addPending);const [error,setError]=useState('');const [label,setLabel]=useState('');const [fail,setFail]=useState(false);const next=React.useRef(0); async function submit(data){const parsed=parseLabel(data);if(parsed.error){setError(parsed.error);return;}const id=++next.current;setError('');add({id,label:parsed.label});await delay();const response=await saveRepair(parsed.label,data.has('fail'));if(response.error){setError(response.error);return;}startTransition(()=>setItems(old=>confirmRepair(old,{id,label:response.label})));setLabel('');} return <section><form action={submit}><label>Repair label <input name="label" value={label} onChange={e=>setLabel(e.target.value)}/></label><label><input name="fail" type="checkbox" checked={fail} onChange={e=>setFail(e.target.checked)}/> Simulate failure</label><Submit/></form><p role="status">{error}</p><ul>{view.map(item=><li key={item.id}>{item.label}{item.pending?' (pending)':''}</li>)}</ul></section>;}Enter Desk lamp and submit. The temporary row appears with a pending marker; success replaces it with the normalized label Desk lamp. Check Simulate failure and submit another label: the temporary row should disappear once the Action settles, and the error message appears. The confirmed array was not updated on failure, so rollback is automatic; no saved-state snapshot is required. In this fixture, the input text is retained on failure and cleared on success. Editing it during pending can be overwritten by the later success reset; the next example prevents this. IDs are local to the mounted demo, not durable server identifiers. A disabled submit control supports a single-user teaching path, not a concurrency guarantee.
Bound the submission and expose retry feedback
import React,{useState,useTransition,startTransition,useActionState,useOptimistic} from 'react';import {useFormStatus} from 'react-dom';const delay=()=>new Promise(resolve=>setTimeout(resolve,600));function parseLabel(data){ const value=data.get('label'); if(typeof value!=='string') return {error:'Enter a repair label.'}; const label=value.trim(); if(!label||label.length>40) return {error:'Use 1–40 characters.'}; return {label};}function Fields({draft,setDraft}){const {pending}=useFormStatus();return <><label>Repair label <input name="label" value={draft} onChange={e=>setDraft(e.target.value)} disabled={pending}/></label><button type="submit" disabled={pending}>{pending?'Saving…':'Save'}</button></>;}export default function App(){const [draft,setDraft]=useState('');const [base,setBase]=useState('No saved repair');const [view,show]=useOptimistic(base);const [message,setMessage]=useState('');const [fail,setFail]=useState(false); async function save(data){const parsed=parseLabel(data);if(parsed.error){setMessage(parsed.error);return;}show(parsed.label+' (pending)');setMessage('');await delay();if(fail){setMessage('Not saved. Turn off failure simulation and retry.');return;}startTransition(()=>setBase(parsed.label));setDraft('');setMessage('Saved.');} return <section><label><input type="checkbox" checked={fail} onChange={e=>setFail(e.target.checked)}/> Simulate failure for next submit</label><form action={save}><Fields draft={draft} setDraft={setDraft}/></form><p>{view}</p><p role="status">{message}</p></section>;}The Action captures the fail setting from the render that supplied the handler; changing the external switch during a pending operation does not rewrite that attempt. The draft input is disabled only while submitting; failure restores the last confirmed label and retains the draft for retry. A real service needs stable request IDs, server-side idempotency, authorization, conflict handling and authoritative responses. Multiple optimistic writes can settle in an unexpected order; design explicit ordering or conflict rules before allowing them. Practice: simulate failure, retry with success, and explain why neither a disabled button nor temporary optimism proves the server wrote exactly once.