optimystic
v0.1.1
Published
Optimistic UI for React 19 Actions: rollback on error, retry with backoff, and a queue for concurrent mutations. ~2kB, no cache, no data layer.
Maintainers
Readme
optimystic
Optimistic UI for React 19 — rollback you control, retry with backoff, and a queue so concurrent writes layer instead of clobbering each other.
1.8 kB min+gzip · zero dependencies · React 19 peer only

npm install optimysticWhy this exists
React 19's useOptimistic shows a patch and then silently drops it when the action finishes. That is the right primitive, but shipping optimistic UI needs four more things, and most apps hand-roll the same fifty lines to get them:
The error has nowhere to go. When the write fails, the patch just vanishes. No callback, no state, nothing to render "couldn't save" against.
No retry. One flaky request and the user's edit is gone, even though a second attempt 400ms later would have worked.
Concurrent writes fight. Two rapid edits produce a UI where one silently wins, because each optimistic snapshot was taken from stale state.
The gap after success. The server said yes, but new props haven't arrived yet. Drop the patch at that moment and the old value flashes back on screen.
optimystic handles exactly those four. It is not a cache, not a data layer, and has no opinion about how you fetch.
Quick start
'use client'
import { useOptimisticQueue } from 'optimystic'
export function Todos({ todos }: { todos: Todo[] }) {
const { data, mutate, failed, retry, rollback, isPending } = useOptimisticQueue({
data: todos, // confirmed state
apply: (list, text) => [...list, draft(text)], // pure optimistic patch
commit: (text) => addTodo(text), // the real write
retry: 3,
failureMode: 'retain', // keep failures on screen
})
return (
<>
<form action={(formData) => mutate(String(formData.get('text')))}>
<input name="text" />
<button disabled={isPending}>Add</button>
</form>
<ul>
{data.map((todo) => <li key={todo.id}>{todo.text}</li>)}
</ul>
{failed.map((mutation) => (
<p key={mutation.id} role="alert">
Couldn't save "{mutation.variables}".
<button onClick={() => retry(mutation.id)}>Retry</button>
<button onClick={() => rollback(mutation.id)}>Discard</button>
</p>
))}
</>
)
}mutate returns a promise that always resolves — { ok, id, error, aborted } — so it composes with <form action>, useActionState and plain event handlers without try/catch gymnastics.
The single-value case
For a like button, a toggle, an inline rename — anywhere the patch is just "replace it with what the user picked":
import { useOptimisticValue } from 'optimystic'
const { value: liked, set, isPending, error } = useOptimisticValue({
value: post.liked,
commit: (next) => setLiked(post.id, next),
retry: 2,
})
<button onClick={() => set(!liked)} aria-busy={isPending}>
{liked ? 'Liked' : 'Like'}
</button>Writes are serialised, so rapid clicking sends every value in order and the last one the user chose is the one that sticks.
How it works
Confirmed state is never mutated. Each in-flight mutation is a record holding its own variables, and what you render is apply folded over those records in submission order:
rendered = apply(apply(apply(confirmed, m1), m2), m3)A mutation that succeeds leaves the fold. A mutation that fails either leaves it (rollback) or stays with its error attached (retain). Because patches layer rather than snapshot, two concurrent edits both stay visible and one settling early never erases the other.
Each record moves through three states, visible in mutations:
| status | meaning |
| --- | --- |
| pending | the commit is in flight, or waiting between retries |
| settling | the server said yes; the patch is held until confirmed state catches up, so nothing flickers |
| error | every attempt failed and failureMode: 'retain' kept the patch on screen |
API
useOptimisticQueue(options)
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| data | S | — | Confirmed state you own — props, a query cache, a server component. |
| initialData | S | — | Use instead of data to let the hook own state; successful patches fold in permanently. |
| apply | (state: S, variables: V) => S | — | Pure reducer producing the optimistic next state. Must not mutate state. |
| commit | (variables: V, ctx) => Promise<unknown> | — | The real write. ctx carries { id, attempt, signal }. |
| mode | 'parallel' \| 'serial' | 'parallel' | 'serial' queues mutations FIFO. |
| failureMode | 'rollback' \| 'retain' | 'rollback' | 'retain' keeps the failed patch visible with status: 'error'. |
| retry | number \| RetryPolicy | none | 3, or { attempts, delay, backoff, maxDelay, shouldRetry }. |
| settleFor | number | 5000 | Ms to hold a succeeded patch while waiting for confirmed state. |
| isSettled | (data: S, variables: V) => boolean | — | Decide precisely when confirmed state has absorbed a patch. |
| onSuccess | (variables, result) => void | — | Fired once the commit resolves. |
| onError | (error, variables, mutation) => void | — | Fired after the final attempt fails. |
| onSettled | (variables) => void | — | Fired on success or final failure. |
Returns:
| Field | Type | Description |
| --- | --- | --- |
| data | S | Confirmed state with every live patch folded on top. |
| mutate | (variables: V) => Promise<MutateResult> | Fire a mutation. Never rejects. |
| mutations | Mutation[] | Every live record: pending, settling and retained failures. |
| failed | Mutation[] | Just the failures. |
| isPending | boolean | Any commit in flight. |
| hasFailed | boolean | Any retained failure. |
| retry | (id?: string) => void | Retry one failure, or all of them. |
| rollback | (id?: string) => void | Drop one mutation (aborting it if in flight), or all. |
| reset | () => void | Abort everything and clear the queue. |
useOptimisticValue(options)
Takes value (or initialValue), commit, and the same retry, failureMode, settleFor and callbacks. Returns { value, set, isPending, error, failed, retry, rollback, reset }.
Retry policy
retry: {
attempts: 3, // total attempts including the first
delay: 300, // base delay in ms
backoff: 'exponential', // or 'fixed'
maxDelay: 30_000,
shouldRetry: (error, attempt, variables) => error.status >= 500,
}Recipes
Next.js Server Actions
'use client'
const { data, mutate } = useOptimisticQueue({
data: comments,
apply: (list, body) => [...list, { id: 'pending', body, author: me }],
commit: (body) => postComment(postId, body), // 'use server' action
retry: 2,
})
<form action={(formData) => mutate(String(formData.get('body')))}>Optimistic delete
const { data, mutate } = useOptimisticQueue({
data: files,
apply: (list, id) => list.filter((file) => file.id !== id),
commit: (id) => deleteFile(id),
failureMode: 'rollback', // the row reappears if the delete fails
})Don't retry a 4xx
retry: {
attempts: 4,
shouldRetry: (error) => !(error instanceof HttpError) || error.status >= 500,
}Cancel an in-flight write
commit receives an AbortSignal that fires when the mutation is rolled back, reset, or the component unmounts:
commit: (text, { signal }) =>
fetch('/api/todos', { method: 'POST', body: text, signal }),Gotchas
Add 'use client' to the file where you call these hooks, in a Next.js App Router project. The package ships the directive, but your own component file needs it too.
Pass a stable data reference. After a commit succeeds the patch is held until confirmed state catches up, and the hook detects that by reference identity. Props, a query cache value or a useMemo are fine; an array you recompute in the component body every render is not. If you can't make it stable, pass isSettled and the hook will ask you directly:
isSettled: (todos, text) => todos.some((t) => t.text === text)apply must be pure. It runs on every render while a mutation is live. Copy, don't mutate.
mutate never rejects. Check result.ok instead of wrapping it in try/catch.
When not to use this
If you already use TanStack Query or SWR, their mutation APIs cover this ground and are wired into the cache — use those. optimystic is for apps whose writes are Server Actions, fetch or an RPC client, where pulling in a caching layer just to get rollback is too much.
Requirements
React 19 or newer (it uses nothing exotic, but the Actions-era patterns are the point). TypeScript types are included. Ships ESM and CJS with a "use client" directive preserved in both.
Development
npm install
npm test # vitest, jsdom
npm run verify # typecheck + test + build + dist sanity checkverify guards the three things that quietly break a React library after publish: that "use client" survives into dist, that React is externalised rather than bundled, and that types are emitted.
Contributing
Issues and pull requests welcome. Run npm run verify before opening one, and add a changeset with npx changeset describing the change.
License
MIT © Somya Abichandani
