Optimistic Updates
Optimistic updates change the UI right after a user action, before the server answers. If the request fails, the change
is reverted. HyperFetch splits this in two: a helper describes the change of a cached request, and .rollback()
describes the undo. Core applies the change, runs the undo when needed, refreshes the data afterwards and protects the
change from stale responses - for send(), $hooks and React hooks alike.
- Describe, don't orchestrate:
optimistic(getTodos).patch(todoId, payload)replaces snapshots and hand-written cache updates. - Explicit undo:
.rollback()sits next to the change it reverts. Core runs it once, at the right moment. - Always correct in the end: targets are refetched once the last pending mutation on them settles.
- No stale overwrites: a fetch that started before the mutation settled never overwrites the optimistic value.
- Typed end to end: helpers are typed by the target's response,
.commit()by the mutation's response.
Quick start
Return the changes from setOptimistic. The callback receives the mutation's params, queryParams and payload.
import { optimistic } from "@hyper-fetch/core";
const getTodos = client.createRequest<{ response: Todo[] }>()({ endpoint: "/todos" });
const toggleTodo = client
.createRequest<{ response: Todo; payload: { completed: boolean } }>()({
endpoint: "/todos/:todoId",
method: "PATCH",
})
.setOptimistic(({ params, payload }) => [
optimistic(getTodos)
.patch(params.todoId, payload)
.rollback(({ data, previous }) => {
const before = previous.find((todo) => todo.id === Number(params.todoId));
return data.map((todo) => (todo.id === Number(params.todoId) && before ? before : todo));
}),
]);
Components need nothing optimistic-specific:
function Todos() {
const { data: todos } = useFetch(getTodos);
const { submit } = useSubmit(toggleTodo);
return todos?.map((todo) => (
<div key={todo.id} onClick={() => submit({ params: { todoId: todo.id }, payload: { completed: !todo.completed } })}>
{todo.title}
</div>
));
}
When setOptimistic returns synchronously, the cache changes within the submit() / send() call, so the list
re-renders in the same tick.
Helpers
| Helper | Use |
|---|---|
set(updater) | Anything else - receives and returns the data |
patch(match, fields) | Merge fields into matching list items |
insert(item, { at }) | Add an item at "end" (default), "start" or an index |
remove(match) | Remove matching items |
increment(field, by) / increment(match, field, by) | Counters on the data or on matching items |
match is a predicate, or a plain value compared with the item's id. Numbers and strings match each other, so a route
param "1" matches the id 1. Compare another field with { key }:
optimistic(getTodos).remove(params.todoId);
optimistic(getTodos).patch((todo) => todo.listId === params.listId, { archived: true });
optimistic(getTodos).remove(params.slug, { key: "slug" });
Targets
optimistic(getUser.setParams({ userId }))- one cache entry. A target whose params are not set is a compile error.optimistic.all(getUsers)- every cached variant of the request, whatever the query params: filters, sorting and all pages of infinite lists..list("field")- the list helpers for an array inside an object response:
optimistic(getFeed).list("items").insert(post, { at: "start" });
The list helpers exist when the target's data is an array, increment(field, by) and .list() when it is an object.
Unchanged items keep their references, and a helper that matches nothing does not write to the cache.
Rollback
Core never infers an undo - an updater is opaque, and items cannot be found reliably after other changes. You write
the undo in .rollback(); core runs it.
.rollback(({ data, previous, reason, response, request }) => next):
| Field | Description |
|---|---|
data | The target's data now, after other mutations and server responses |
previous | The target's data just before this change was applied - use it to look values up |
reason | "error", "abort" or "removed" (from the queue) |
response | The mutation's failed response. Absent for "removed" |
request | The mutation request |
It returns the new data. Returning nothing leaves the data as it is, so a rollback can be a pure side effect. It must be synchronous.
// Re-add a removed item
optimistic(getTodos)
.remove(params.todoId)
.rollback(({ data, previous }) => {
const removed = previous.find((todo) => todo.id === Number(params.todoId));
return removed ? [...data, removed] : data;
});
// Opposite increment
optimistic(getStats)
.increment("total", -1)
.rollback(({ data }) => ({ ...data, total: data.total + 1 }));
// Keep a failed message in the list, marked for retry
optimistic(getMessages)
.insert(message)
.rollback(({ data, reason }) =>
reason === "error"
? data.map((item) => (item.id === message.id ? { ...item, status: "failed" } : item))
: data.filter((item) => item.id !== message.id),
);
// No .rollback(): on failure the user is simply refetched
optimistic(getUser.setParams({ userId: params.userId })).set((user) => ({ ...user, ...payload }));
dataprevious is a snapshot from before the change. Returning it whole would discard everything that happened since, such
as other mutations on the same list. Use it only to look old values up.
Commit
.commit(({ data, response, request }) => next) runs on success, for example to swap a temporary item for the server's.
Use the optimistic builder passed to the callback to type response with the mutation's response:
const createTodo = client
.createRequest<{ response: Todo; payload: NewTodo }>()({ endpoint: "/todos", method: "POST" })
.setOptimistic(({ payload, optimistic }) => {
const temp = { id: -Date.now(), ...payload, completed: false };
return [
optimistic(getTodos)
.insert(temp)
.commit(({ data, response }) => data.map((todo) => (todo.id === temp.id ? response.data : todo)))
.rollback(({ data }) => data.filter((todo) => todo.id !== temp.id)),
];
});
When things settle
Everything below is triggered by core, also when the component that submitted has unmounted.
| Outcome | What happens | Then |
|---|---|---|
| Success | Each .commit() runs | Targets refresh |
| Final error | Each .rollback() runs, in reverse order of the changes | Targets refresh |
Final error, rollbackOnError says no | The change stays, no rollback | Nothing |
| Abort, or removed from the queue | Each .rollback() runs, in reverse order | Targets refresh |
| Will retry, or waits offline to resend | The change stays | Nothing yet |
- No flicker on success. The optimistic value is the cached value until the refresh returns.
- Refresh waits for the last one. With several mutations pending on one key, the key is refreshed once, after the
last of them settles. A refresh is a cache invalidation, so mounted
useFetchhooks refetch it. - Stale responses are discarded. While a mutation that changed a key is pending, and for fetches that started
before it settled, fetch responses are not written to that key. The refresh supplies current data. Manual
cache.set/cache.updatecalls are never affected, and a key that had no data when the change was applied is not held back, so a first load always lands. - The refresh is the safety net. An undo that is slightly off is corrected as soon as the refetch returns.
- No data, no change. A target without cached data is left alone and its
.rollback()is not called; it is still refreshed. - Aborting from
useSubmitremoves the request from the queue, so rollbacks receive"removed".request.abort()cancels the running request and reports"abort". - User code can't break a request. When a helper,
.commit()or.rollback()throws (or returns a promise), the request completes, the other changes still settle and the target is refreshed. The error is logged and thrown from a timer, outside of the request lifecycle, sowindow.onerrororuncaughtExceptionhandlers still see it.
Options and forms
setOptimistic accepts an array of changes, or an object that combines them with the rest:
toggleTodo.setOptimistic(({ params, payload }) => ({
updates: [optimistic(getTodos).patch(params.todoId, payload)],
// Delivered as `mutationContext` to the lifecycle callbacks
context: { todoId: params.todoId },
// A hand-written rollback for anything outside the cache, runs after the helpers' rollbacks
rollback: ({ reason }) => toast(`Not saved (${reason})`),
// Keep the change when the server rejects it with a conflict
rollbackOnError: ({ response }) => response.status !== 409,
// Don't refresh the targets afterwards
revalidate: false,
}));
| Field | Default | Description |
|---|---|---|
updates | - | Changes built with optimistic() |
context | - | Typed mutationContext for the lifecycle callbacks |
rollback | - | Hand-written undo, receives { reason, response, request } |
invalidate | - | Requests invalidated on success |
rollbackOnError | true | true, false or ({ response, request }) => boolean - final errors only |
revalidate | true | Refresh the targets after the last pending mutation settles |
Per call
Pass changes for one call - they replace the request's own setOptimistic:
submit({
params: { todoId },
payload,
optimistic: [optimistic(getTodos).patch(todoId, payload)],
});
// Or for every submit of one hook
const { submit } = useSubmit(toggleTodo, {
optimistic: ({ params, payload }) => [optimistic(getTodos).patch(params.todoId, payload)],
});
request.send({ optimistic }) works the same outside React.
Migrating from the hand-written form
The object form - snapshot the cache, update it, return { context, rollback, invalidate } - keeps working unchanged.
Its rollback now also receives { reason, response, request }; a rollback without arguments is unaffected.
To move to the helpers:
.setOptimistic(({ client, payload, request }) => {
const todoId = Number(request.params?.todoId);
const previousItem = client.cache.get(getTodos.cacheKey)?.data?.find((t) => t.id === todoId);
client.cache.update(getTodos, (prev) => ({
...prev,
data: prev.data.map((t) => (t.id === todoId ? { ...t, ...payload } : t)),
}));
return {
rollback: () => {
if (previousItem) {
client.cache.update(getTodos, (prev) => ({
...prev,
data: prev.data.map((t) => (t.id === todoId ? previousItem : t)),
}));
}
},
invalidate: [getTodos],
};
});
.setOptimistic(({ params, payload }) => [
optimistic(getTodos)
.patch(params.todoId, payload)
.rollback(({ data, previous }) => {
const before = previous.find((t) => t.id === Number(params.todoId));
return data.map((t) => (t.id === Number(params.todoId) && before ? before : t));
}),
]);
- Replace the cache update with a helper, and the snapshot with
previousinside.rollback(). - Drop
invalidatefor the targets - they are refreshed automatically. Keep it for other requests. - Keep
contextand side-effect rollbacks by returning the object form withupdates.
- Describe each change with
optimistic(target)and a helper:set,patch,insert,remove,increment. - Write the undo in
.rollback()and success follow-ups in.commit()- core runs them exactly once. - Targets are refreshed once after the last pending mutation, and stale fetch responses are discarded.
- Use
optimistic.all()for every filter and page of a list, and.list("field")for lists inside objects. - Pass changes per call with the
optimisticoption ofsend(),submit()oruseSubmit.
Next Steps
For concurrent mutations on one list, toggles and several caches at once, see the Advanced Optimistic Patterns guide.
