frontend-optimistic-mutations
Что он делает
Этот скилл помогает сделать обновления на экране мгновенными для пользователя. Он сразу обновляет интерфейс и, если что-то пошло не так, отменяет изменение без следа.
Когда использовать
- ✓При отметке элемента как выполненного.
- ✓При изменении статуса заказа.
- ✓При изменении порядка элементов в списке.
Ссылка на скилл
https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/frontend-optimistic-mutations/SKILL.mdСкопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.
Как использовать
Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.
Готовое сообщение для вставки
Для Claude Code, Codex или Cursor: запустите в папке проекта, и скилл установится.
Скачайте SKILL.md и положите его в папку скиллов вашего агента.
Пример запроса к вашему ИИ
“Сделай так, чтобы отметка счета как «оплачен» происходила мгновенно, но откатывалась при ошибке.”
5 новых скиллов в неделю. 1 минута чтения.
Как это работает
Когда вы вносите изменение, экран обновляется сразу. Если изменение не удалось отправить на сервер, экран возвращается к предыдущему состоянию, как будто ничего не было.
Технический текст (оригинальный SKILL.md)
Оригинальный текст автора на английском, прямо с GitHub.
Frontend Optimistic Mutations (the write path)
When to Use
Use this skill when you need a portable, framework-agnostic discipline for the write path of any React or React Native app using a query/cache layer. Codifies the optimistic-update lifecycle (cancel in-flight queries → snapshot every affected cache → patch instantly → roll back verbatim on error → invalidate on...
Portable skill — readable by Claude Code, OpenCode, Codex, Cursor, Windsurf, and others. This skill describes the discipline of the write path — optimistic updates, rollback, idempotency, cache coherence — not a UI library or a styling system. It builds directly on the frontend-data-contracts skill (writes go through the typed client) and the frontend-architecture skill (mutations live in
modules/{feature}/hooks/, keyed by a factory).
The goal: a write feels instant (the UI reflects it before the server confirms), is safe (a failure restores the exact prior state, and a retry never double-charges), and leaves the cache coherent (the detail view and every list page agree). All three at once — that's the craft.
0. The five core ideas
- The optimistic lifecycle is fixed. cancel → snapshot → patch → (error: roll back) → (settle: invalidate). Every optimistic mutation follows the same five beats.
- Roll back verbatim. On failure, restore the exact snapshot taken before the patch — not a "best guess" re-derivation. Keep the snapshot in mutation context.
- Idempotency is generated once, not per attempt. The key is created at form init (or first intent), so a network retry replays the original server response instead of performing the action twice.
- Caches move in lock-step. A status change patches the detail cache and every list page that contains the entity, so badges never disagree across surfaces.
- Server state never enters the client store. Optimistic state lives in the query cache, not Zustand/Redux. The cache is the single source of truth for server data (per frontend-architecture §4).
1. When to be optimistic (and when not)
| Situation | Strategy |
|---|---|
| High-confidence, low-conflict write (toggle status, like, mark-paid, reorder) | Optimistic — patch immediately, roll back on error. |
| Create that returns a server-generated id/number/total | Pending state, then setQueryData from the server response. A temporary optimistic row is optional; reconcile on success. |
| Destructive or hard-to-reverse write (delete with cascade, send money) | Confirm first, then optimistic or pending — never silent-optimistic. |
| Write whose result the user can't see yet (background job) | Pending + toast, invalidate when done. No optimistic patch. |
Optimism is a UX tool for writes you're confident will succeed. If failure is common or expensive to undo, prefer a pending state.
2. The optimistic lifecycle (TanStack Query)
The canonical shape. Each beat has a job; skipping one breaks correctness.
// modules/invoice/hooks/useInvoiceMutations.ts
interface MarkPaidContext {
previousInvoice: Invoice | undefined; // detail snapshot
previousLists: Array<[readonly unknown[], InvoiceListResponse]>; // every list page snapshot
}
export function useMarkInvoicePaid() {
const queryClient = useQueryClient();
const notifyError = useApiErrorToast();
return useMutation<Invoice, ApiError, { id: InvoiceId }, MarkPaidContext>({
mutationFn: ({ id }) => apiClient.post<Invoice>(INVOICE_API.markPaid(id)),
// 1 + 2 + 3: cancel in-flight reads, snapshot, patch
onMutate: async ({ id }) => {
await queryClient.cancelQueries({ queryKey: invoiceKeys.all }); // (1) no late refetch clobber
const detailKey = invoiceKeys.detail(id);
…
Частые вопросы
Что означает «оптимистичное обновление»?
Это когда интерфейс обновляется сразу, чтобы отразить изменение, еще до того, как сервер подтвердит, что оно успешно сохранено. Это похоже на заполнение формы, после которой сразу появляется надпись «сохранено», хотя система еще фактически ничего не сохранила.
Что такое «откат» (rollback)?
Это возможность вернуть изменение к точному состоянию, которое было до него, если произошла ошибка. Так пользователь не останется с несогласованными или неверными данными.
Почему важно, чтобы списки и детальные страницы были согласованы?
Чтобы информация была одинаковой во всем приложении. Если вы отметили элемент как оплаченный в списке, все остальные места, где этот элемент показан (например, страница с подробностями), тоже должны сразу отображать это изменение.
Подробности
Оригинальное описание автора
A portable, framework-agnostic discipline for the write path of any React or React Native app using a query/cache layer.
Популярность
- Звёзды на GitHub
- 48k
- Место в рейтинге
- #4671
- Лицензия
- MIT
- Обновлён
- 15.10.2026
Комментарии
- …
Другие скиллы из этого репозитория
00-andruia-consultant
48kПомогает агенту начинать или улучшать ИИ-проекты: анализирует код, подбирает инструменты и составляет план на испанском.
007
48kАгент проводит аудит безопасности и моделирование угроз для защиты проектов.
10-andruia-skill-smith
48kПомогает агенту создавать и улучшать ИИ-инструменты: описание работы, документация и проверка структуры.
20-andruia-niche-intelligence
48kАгент составляет обзор отрасли: контекст, правила, паттерны использования и риски по надёжным источникам.
Похожие скиллы
angular-developer
280kПомогает агенту писать код на Angular и советовать по структуре проекта. Полезен для новых проектов, создания частей кода и улучшения производительности.
frontend-a11y
280kПомогает агенту делать веб-интерфейсы доступными для всех, чтобы сайты и приложения работали с программами чтения с экрана и клавиатурой.
frontend-patterns
280kАгент применяет современные паттерны фронтенд-разработки: оптимизирует производительность, управляет состоянием и следует практикам React и Next.js.