[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7A5AY2A5SFEKENHX9CQSJS1":3,"skill-same:01M7A5AY2A5SFEKENHX9CQSJS1":53},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":30,"commitSha":31,"skillDirectory":32,"forksCount":33,"repositoryHtmlUrl":34,"repositoryHomepageUrl":6,"ownerHtmlUrl":35,"ownerBlogUrl":36,"ownerDescription":37,"updatedAt":38,"install":39,"resources":52},"01M7A5AY2A5SFEKENHX9CQSJS1","frontend-optimistic-mutations",null,"A portable, framework-agnostic discipline for the write path of any React or React Native app using a query\u002Fcache layer. Codifies the optimistic-update lifecycle (cancel in-flight queries → snapshot every affected cache → patch instantly → roll back verbatim on error → invalidate on...","MHassan0000\u002FSkills","MHassan0000","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F224296448?v=4","01M7A14DTC1EZCRN04582533RD","Muhammad Hassan Yousaf","01M7A14DV10KTW8NHQTJPD08X0",1,"MIT","https:\u002F\u002Fgithub.com\u002FMHassan0000\u002FSkills\u002Fblob\u002Fmain\u002FClaude\u002Fantigravity skills\u002Fagentic-awesome-skills\u002Fskills\u002Ffrontend-optimistic-mutations\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: frontend-optimistic-mutations\ndescription: A portable, framework-agnostic discipline for the write path of any React or React Native app using a query\u002Fcache layer. Codifies the optimistic-update lifecycle (cancel in-flight queries → snapshot every affected cache → patch instantly → roll back verbatim on error → invalidate on...\nrisk: critical\nsource: https:\u002F\u002Fgithub.com\u002Fstareezy-1\u002Ffrontend-architecture-skill\u002Ftree\u002Fmain\u002Fskills\u002Ffrontend-optimistic-mutations\nsource_repo: stareezy-1\u002Ffrontend-architecture-skill\nsource_type: community\ndate_added: 2026-07-01\nlicense: MIT\nlicense_source: https:\u002F\u002Fgithub.com\u002Fstareezy-1\u002Ffrontend-architecture-skill\u002Fblob\u002Fmain\u002FLICENSE\n---\n\n# Frontend Optimistic Mutations (the write path)\n## When to Use\n\nUse this skill when you need a portable, framework-agnostic discipline for the write path of any React or React Native app using a query\u002Fcache layer. Codifies the optimistic-update lifecycle (cancel in-flight queries → snapshot every affected cache → patch instantly → roll back verbatim on error → invalidate on...\n\n\n> Portable skill — readable by Claude Code, OpenCode, Codex, Cursor, Windsurf, and others.\n> This skill describes the **discipline of the write path** — optimistic updates, rollback,\n> idempotency, cache coherence — not a UI library or a styling system. It builds directly on the\n> **frontend-data-contracts** skill (writes go through the typed client) and the\n> **frontend-architecture** skill (mutations live in `modules\u002F{feature}\u002Fhooks\u002F`, keyed by a factory).\n\nThe goal: a write **feels instant** (the UI reflects it before the server confirms), is **safe**\n(a failure restores the exact prior state, and a retry never double-charges), and leaves the cache\n**coherent** (the detail view and every list page agree). All three at once — that's the craft.\n\n---\n\n## 0. The five core ideas\n\n1. **The optimistic lifecycle is fixed.** cancel → snapshot → patch → (error: roll back) → (settle: invalidate). Every optimistic mutation follows the same five beats.\n2. **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.\n3. **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.\n4. **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.\n5. **Server state never enters the client store.** Optimistic state lives in the query cache, not Zustand\u002FRedux. The cache is the single source of truth for server data (per frontend-architecture §4).\n\n---\n\n## 1. When to be optimistic (and when not)\n\n| Situation                                                                     | Strategy                                                                                                                       |\n| ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |\n| High-confidence, low-conflict write (toggle status, like, mark-paid, reorder) | **Optimistic** — patch immediately, roll back on error.                                                                        |\n| Create that returns a server-generated id\u002Fnumber\u002Ftotal                        | **Pending state**, then `setQueryData` from the server response. A temporary optimistic row is optional; reconcile on success. |\n| Destructive or hard-to-reverse write (delete with cascade, send money)        | **Confirm first**, then optimistic _or_ pending — never silent-optimistic.                                                     |\n| Write whose result the user can't see yet (background job)                    | **Pending + toast**, invalidate when done. No optimistic patch.                                                                |\n\nOptimism is a UX tool for writes you're confident will succeed. If failure is common or expensive to\nundo, prefer a pending state.\n\n---\n\n## 2. The optimistic lifecycle (TanStack Query)\n\nThe canonical shape. Each beat has a job; skipping one breaks correctness.\n\n```ts\n\u002F\u002F modules\u002Finvoice\u002Fhooks\u002FuseInvoiceMutations.ts\ninterface MarkPaidContext {\n  previousInvoice: Invoice | undefined; \u002F\u002F detail snapshot\n  previousLists: Array\u003C[readonly unknown[], InvoiceListResponse]>; \u002F\u002F every list page snapshot\n}\n\nexport function useMarkInvoicePaid() {\n  const queryClient = useQueryClient();\n  const notifyError = useApiErrorToast();\n\n  return useMutation\u003CInvoice, ApiError, { id: InvoiceId }, MarkPaidContext>({\n    mutationFn: ({ id }) => apiClient.post\u003CInvoice>(INVOICE_API.markPaid(id)),\n\n    \u002F\u002F 1 + 2 + 3: cancel in-flight reads, snapshot, patch\n    onMutate: async ({ id }) => {\n      await queryClient.cancelQueries({ queryKey: invoiceKeys.all }); \u002F\u002F (1) no late refetch clobber\n\n      const detailKey = invoiceKeys.detail(id);\n      const previousInvoice = queryClient.getQueryData\u003CInvoice>(detailKey); \u002F\u002F (2) snapshot detail\n      if (previousInvoice) {\n        queryClient.setQueryData\u003CInvoice>(detailKey, {\n          \u002F\u002F (3) patch detail\n          ...previousInvoice,\n          status: InvoiceStatus.Paid,\n        });\n      }\n\n      const previousLists: MarkPaidContext[\"previousLists\"] = [];\n      for (const [key, list] of queryClient.getQueriesData\u003CInvoiceListResponse>(\n        {\n          queryKey: invoiceKeys.lists(),\n        },\n      )) {\n        if (!list) continue;\n        previousLists.push([key, list]); \u002F\u002F (2) snapshot each page\n        if (!list.invoices.some((i) => i.id === id)) continue;\n        queryClient.setQueryData\u003CInvoiceListResponse>(key, {\n          \u002F\u002F (3) patch matching row\n          ...list,\n          invoices: list.invoices.map((i) =>\n            i.id === id ? { ...i, status: InvoiceStatus.Paid } : i,\n          ),\n        });\n      }\n      return { previousInvoice, previousLists };\n    },\n\n    \u002F\u002F 4: roll back verbatim\n    onError: (error, { id }, ctx) => {\n      if (ctx?.previousInvoice)\n        queryClient.setQueryData(invoiceKeys.detail(id), ctx.previousInvoice);\n      for (const [key, list] of ctx?.previousLists ?? [])\n        queryClient.setQueryData(key, list);\n      notifyError(error);\n    },\n\n    \u002F\u002F 5: invalidate so authoritative server state (paidAt, aggregates) refetches\n    onSettled: (_d, _e, { id }) => {\n      void queryClient.invalidateQueries({ queryKey: invoiceKeys.detail(id) });\n      void queryClient.invalidateQueries({ queryKey: invoiceKeys.lists() });\n    },\n  });\n}\n```\n\n**Why each beat:**\n\n- **cancel** — without it, a query that was already in flight can resolve _after_ your patch and overwrite the optimistic state.\n- **snapshot** — the only safe rollback source; never reconstruct prior state by hand.\n- **patch** — the instant UX; mutate detail **and** lists together (§4).\n- **roll back** — restore snapshots verbatim, then surface the typed `ApiError`.\n- **invalidate on settle** — success or failure, refetch so server-computed fields (timestamps, totals) are authoritative. Settle, not just success: a failed write may still have changed server state.\n\n---\n\n## 3. Non-optimistic writes: create with server-owned fields\n\nA create that returns an id\u002Fnumber\u002Ftotal can't be fully optimistic. Run it as a pending mutation and\nseed the cache from the response.\n\n```ts\nexport function useCreateInvoice() {\n  const queryClient = useQueryClient();\n  return useMutation\u003CInvoice, ApiError, CreateInvoiceInput>({\n    mutationFn: ({ document, idempotencyKey }) =>\n      apiClient.post\u003CInvoice>(\"\u002Finvoices\", document, { idempotencyKey }),\n    onSuccess: (invoice) => {\n      queryClient.setQueryData(invoiceKeys.detail(invoice.id), invoice); \u002F\u002F seed detail\n      void queryClient.invalidateQueries({ queryKey: invoiceKeys.lists() }); \u002F\u002F refresh lists\n    },\n    onError: (error) => notifyError(error),\n  });\n}\n```\n\n---\n\n## 4. Cache coherence (lock-step detail + lists)\n\nA single entity appears in many caches: its detail, and every filtered\u002Fpaginated list page. An\noptimistic patch must touch **all of them** or surfaces disagree. Use a **hierarchical key factory**\n(from frontend-architecture §4.3) so you can target precisely.\n\n```ts\nexport const invoiceKeys = {\n  all: [\"invoices\"] as const,\n  lists: () => [...invoiceKeys.all, \"list\"] as const,\n  list: (p: IListParams) => [...invoiceKeys.lists(), p] as const,\n  detail: (id: InvoiceId) => [...invoiceKeys.all, \"detail\", id] as const,\n} as const;\n```\n\n- `getQueriesData({ queryKey: invoiceKeys.lists() })` enumerates **every** cached list page so you can patch each.\n- `invalidateQueries({ queryKey: invoiceKeys.lists() })` refreshes them all on settle.\n- `detail(id)` targets exactly one entity.\n\nSnapshot **each** page you touch (keyed by its exact query key) so rollback restores every page\nverbatim, not just the one currently on screen.\n\n---\n\n## 5. Idempotency (safe retries on money-moving writes)\n\nA retried POST must not perform the action twice. Generate the key **once, at form init** (or first\nuser intent), carry it through retries, and let the client send it as a header. The server replays\nthe original response for a repeated key within its window.\n\n```ts\n\u002F\u002F at form initialisation — stable for the lifetime of this attempt\nconst idempotencyKey = useMemo(() => crypto.randomUUID(), []);\n\n\u002F\u002F mutation forwards it; the typed client puts it on the header\napiClient.post\u003CInvoice>(\"\u002Finvoices\", document, { idempotencyKey });\n```\n\n**Hard rules:**\n\n- Generate the key at **intent time**, not inside `mutationFn` (which re-runs per retry → defeats the purpose).\n- The data client auto-detects financial routes and injects the header; an explicit key always wins so retries replay.\n- Pair idempotency with **disabled-while-pending** UI so the user can't fire a second distinct write.\n\n---\n\n## 6. Retry policy\n\n- **Reads:** retry a few times with backoff (default in most query libs) — safe and idempotent.\n- **Writes:** do **not** auto-retry non-idempotent mutations. Retry only when an idempotency key guarantees replay, or only on network errors (status 0), never on 4xx.\n- **Conflicts (409):** don't retry — surface the typed error, invalidate, and let the user re-decide on fresh data.\n\n```ts\nuseMutation({\n  retry: (count, error: ApiError) => error.isNetworkError && count \u003C 2, \u002F\u002F network-only, bounded\n});\n```\n\n---\n\n## 7. Library adapters\n\nThe five-beat lifecycle is the same; the hooks differ.\n\n| Library            | Optimistic mechanism                                                                                                                                       |\n| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| **TanStack Query** | `onMutate` (cancel + snapshot + patch) → `onError` (rollback) → `onSettled` (invalidate). The reference shape above.                                       |\n| **RTK Query**      | `onQueryStarted`: `updateQueryData` returns a `patchResult`; `await queryFulfilled` and call `patchResult.undo()` in `catch`. `invalidatesTags` on settle. |\n| **SWR**            | `mutate(key, optimisticData, { rollbackOnError: true, populateCache, revalidate: true })` — optimistic data + automatic rollback + revalidate.             |\n\nFor **React Native**, all three libraries work unchanged; the cache is the source of truth on\nnative too. Keep mutation hooks DOM-free so they're shareable across web and native.\n\n---\n\n## 8. Conventions checklist (enforce in review)\n\n- [ ] Optimistic mutations follow cancel → snapshot → patch → rollback → invalidate.\n- [ ] `onMutate` cancels in-flight queries before patching.\n- [ ] Rollback restores the **exact** snapshot from context, not a re-derivation.\n- [ ] Detail **and** every affected list page are patched and snapshotted together.\n- [ ] `onSettled` invalidates so server-computed fields are refetched (on success _and_ error).\n- [ ] Idempotency key is generated at intent time and replayed across retries, not regenerated per attempt.\n- [ ] Money-moving \u002F destructive writes confirm first and disable the trigger while pending.\n- [ ] Non-idempotent writes don't auto-retry; 409s surface rather than retry.\n- [ ] Server state stays in the query cache — never copied into a client store.\n- [ ] Query keys come from a hierarchical factory; invalidation is scoped, not global-blunt.\n\n---\n\n## 9. How to apply this skill\n\n**Adding an optimistic mutation:** decide it's safe to be optimistic (§1). Write the five beats\n(§2). Identify every cache the entity lives in and patch\u002Fsnapshot all of them (§4).\n\n**Making a write safe to retry:** generate an idempotency key at form init, thread it through the\nmutation, confirm the client sends it (§5), and set a network-only bounded retry (§6).\n\n**Debugging a flicker \u002F wrong-state-after-write:** check that `onMutate` cancels queries (late\nrefetch clobber) and that `onSettled` invalidates (stale server-computed fields). Check that _all_\nlist pages were patched, not just the visible one.\n\n**Reviewing the write path:** run the checklist in §8. The highest-value catches are missing\n`cancelQueries` (race clobber), partial cache patches (detail\u002Flist disagreement), and idempotency\nkeys generated inside `mutationFn` (no longer protect retries).\n\n---\n\n## Publishing \u002F installing this skill\n\nThis skill follows the Anthropic `SKILL.md` format and is portable across agents.\n\n1. Keep it under `skills\u002Ffrontend-optimistic-mutations\u002FSKILL.md` in a public GitHub repo.\n2. Keep the frontmatter `name` and high-signal `description` — discovery indexes match against it.\n3. Install with: `npx skills add \u003Corg>\u002F\u003Crepo> --skill \"frontend-optimistic-mutations\"`.\n4. Non-`SKILL.md` agents can be pointed here from `AGENTS.md` \u002F `CLAUDE.md`; Kiro can mirror it as a steering file.\n\n## Limitations\n\n- Use this skill only when the task clearly matches its upstream source and local project context.\n- Verify commands, generated code, dependencies, credentials, and external service behavior before applying changes.\n- Do not treat examples as a substitute for environment-specific tests, security review, or user approval for destructive or costly actions.\n","# Frontend Optimistic Mutations (the write path)\n## When to Use\n\nUse this skill when you need a portable, framework-agnostic discipline for the write path of any React or React Native app using a query\u002Fcache layer. Codifies the optimistic-update lifecycle (cancel in-flight queries → snapshot every affected cache → patch instantly → roll back verbatim on error → invalidate on...\n\n\n> Portable skill — readable by Claude Code, OpenCode, Codex, Cursor, Windsurf, and others.\n> This skill describes the **discipline of the write path** — optimistic updates, rollback,\n> idempotency, cache coherence — not a UI library or a styling system. It builds directly on the\n> **frontend-data-contracts** skill (writes go through the typed client) and the\n> **frontend-architecture** skill (mutations live in `modules\u002F{feature}\u002Fhooks\u002F`, keyed by a factory).\n\nThe goal: a write **feels instant** (the UI reflects it before the server confirms), is **safe**\n(a failure restores the exact prior state, and a retry never double-charges), and leaves the cache\n**coherent** (the detail view and every list page agree). All three at once — that's the craft.\n\n---\n\n## 0. The five core ideas\n\n1. **The optimistic lifecycle is fixed.** cancel → snapshot → patch → (error: roll back) → (settle: invalidate). Every optimistic mutation follows the same five beats.\n2. **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.\n3. **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.\n4. **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.\n5. **Server state never enters the client store.** Optimistic state lives in the query cache, not Zustand\u002FRedux. The cache is the single source of truth for server data (per frontend-architecture §4).\n\n---\n\n## 1. When to be optimistic (and when not)\n\n| Situation                                                                     | Strategy                                                                                                                       |\n| ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |\n| High-confidence, low-conflict write (toggle status, like, mark-paid, reorder) | **Optimistic** — patch immediately, roll back on error.                                                                        |\n| Create that returns a server-generated id\u002Fnumber\u002Ftotal                        | **Pending state**, then `setQueryData` from the server response. A temporary optimistic row is optional; reconcile on success. |\n| Destructive or hard-to-reverse write (delete with cascade, send money)        | **Confirm first**, then optimistic _or_ pending — never silent-optimistic.                                                     |\n| Write whose result the user can't see yet (background job)                    | **Pending + toast**, invalidate when done. No optimistic patch.                                                                |\n\nOptimism is a UX tool for writes you're confident will succeed. If failure is common or expensive to\nundo, prefer a pending state.\n\n---\n\n## 2. The optimistic lifecycle (TanStack Query)\n\nThe canonical shape. Each beat has a job; skipping one breaks correctness.\n\n```ts\n\u002F\u002F modules\u002Finvoice\u002Fhooks\u002FuseInvoiceMutations.ts\ninterface MarkPaidContext {\n  previousInvoice: Invoice | undefined; \u002F\u002F detail snapshot\n  previousLists: Array\u003C[readonly unknown[], InvoiceListResponse]>; \u002F\u002F every list page snapshot\n}\n\nexport function useMarkInvoicePaid() {\n  const queryClient = useQueryClient();\n  const notifyError = useApiErrorToast();\n\n  return useMutation\u003CInvoice, ApiError, { id: InvoiceId }, MarkPaidContext>({\n    mutationFn: ({ id }) => apiClient.post\u003CInvoice>(INVOICE_API.markPaid(id)),\n\n    \u002F\u002F 1 + 2 + 3: cancel in-flight reads, snapshot, patch\n    onMutate: async ({ id }) => {\n      await queryClient.cancelQueries({ queryKey: invoiceKeys.all }); \u002F\u002F (1) no late refetch clobber\n\n      const detailKey = invoiceKeys.detail(id);\n      const previousInvoice = queryClient.getQueryData\u003CInvoice>(detailKey); \u002F\u002F (2) snapshot detail\n      if (previousInvoice) {\n        queryClient.setQueryData\u003CInvoice>(detailKey, {\n          \u002F\u002F (3) patch detail\n          ...previousInvoice,\n          status: InvoiceStatus.Paid,\n        });\n      }\n\n      const previousLists: MarkPaidContext[\"previousLists\"] = [];\n      for (const [key, list] of queryClient.getQueriesData\u003CInvoiceListResponse>(\n        {\n          queryKey: invoiceKeys.lists(),\n        },\n      )) {\n        if (!list) continue;\n        previousLists.push([key, list]); \u002F\u002F (2) snapshot each page\n        if (!list.invoices.some((i) => i.id === id)) continue;\n        queryClient.setQueryData\u003CInvoiceListResponse>(key, {\n          \u002F\u002F (3) patch matching row\n          ...list,\n          invoices: list.invoices.map((i) =>\n            i.id === id ? { ...i, status: InvoiceStatus.Paid } : i,\n          ),\n        });\n      }\n      return { previousInvoice, previousLists };\n    },\n\n    \u002F\u002F 4: roll back verbatim\n    onError: (error, { id }, ctx) => {\n      if (ctx?.previousInvoice)\n        queryClient.setQueryData(invoiceKeys.detail(id), ctx.previousInvoice);\n      for (const [key, list] of ctx?.previousLists ?? [])\n        queryClient.setQueryData(key, list);\n      notifyError(error);\n    },\n\n    \u002F\u002F 5: invalidate so authoritative server state (paidAt, aggregates) refetches\n    onSettled: (_d, _e, { id }) => {\n      void queryClient.invalidateQueries({ queryKey: invoiceKeys.detail(id) });\n      void queryClient.invalidateQueries({ queryKey: invoiceKeys.lists() });\n    },\n  });\n}\n```\n\n**Why each beat:**\n\n- **cancel** — without it, a query that was already in flight can resolve _after_ your patch and overwrite the optimistic state.\n- **snapshot** — the only safe rollback source; never reconstruct prior state by hand.\n- **patch** — the instant UX; mutate detail **and** lists together (§4).\n- **roll back** — restore snapshots verbatim, then surface the typed `ApiError`.\n- **invalidate on settle** — success or failure, refetch so server-computed fields (timestamps, totals) are authoritative. Settle, not just success: a failed write may still have changed server state.\n\n---\n\n## 3. Non-optimistic writes: create with server-owned fields\n\nA create that returns an id\u002Fnumber\u002Ftotal can't be fully optimistic. Run it as a pending mutation and\nseed the cache from the response.\n\n```ts\nexport function useCreateInvoice() {\n  const queryClient = useQueryClient();\n  return useMutation\u003CInvoice, ApiError, CreateInvoiceInput>({\n    mutationFn: ({ document, idempotencyKey }) =>\n      apiClient.post\u003CInvoice>(\"\u002Finvoices\", document, { idempotencyKey }),\n    onSuccess: (invoice) => {\n      queryClient.setQueryData(invoiceKeys.detail(invoice.id), invoice); \u002F\u002F seed detail\n      void queryClient.invalidateQueries({ queryKey: invoiceKeys.lists() }); \u002F\u002F refresh lists\n    },\n    onError: (error) => notifyError(error),\n  });\n}\n```\n\n---\n\n## 4. Cache coherence (lock-step detail + lists)\n\nA single entity appears in many caches: its detail, and every filtered\u002Fpaginated list page. An\noptimistic patch must touch **all of them** or surfaces disagree. Use a **hierarchical key factory**\n(from frontend-architecture §4.3) so you can target precisely.\n\n```ts\nexport const invoiceKeys = {\n  all: [\"invoices\"] as const,\n  lists: () => [...invoiceKeys.all, \"list\"] as const,\n  list: (p: IListParams) => [...invoiceKeys.lists(), p] as const,\n  detail: (id: InvoiceId) => [...invoiceKeys.all, \"detail\", id] as const,\n} as const;\n```\n\n- `getQueriesData({ queryKey: invoiceKeys.lists() })` enumerates **every** cached list page so you can patch each.\n- `invalidateQueries({ queryKey: invoiceKeys.lists() })` refreshes them all on settle.\n- `detail(id)` targets exactly one entity.\n\nSnapshot **each** page you touch (keyed by its exact query key) so rollback restores every page\nverbatim, not just the one currently on screen.\n\n---\n\n## 5. Idempotency (safe retries on money-moving writes)\n\nA retried POST must not perform the action twice. Generate the key **once, at form init** (or first\nuser intent), carry it through retries, and let the client send it as a header. The server replays\nthe original response for a repeated key within its window.\n\n```ts\n\u002F\u002F at form initialisation — stable for the lifetime of this attempt\nconst idempotencyKey = useMemo(() => crypto.randomUUID(), []);\n\n\u002F\u002F mutation forwards it; the typed client puts it on the header\napiClient.post\u003CInvoice>(\"\u002Finvoices\", document, { idempotencyKey });\n```\n\n**Hard rules:**\n\n- Generate the key at **intent time**, not inside `mutationFn` (which re-runs per retry → defeats the purpose).\n- The data client auto-detects financial routes and injects the header; an explicit key always wins so retries replay.\n- Pair idempotency with **disabled-while-pending** UI so the user can't fire a second distinct write.\n\n---\n\n## 6. Retry policy\n\n- **Reads:** retry a few times with backoff (default in most query libs) — safe and idempotent.\n- **Writes:** do **not** auto-retry non-idempotent mutations. Retry only when an idempotency key guarantees replay, or only on network errors (status 0), never on 4xx.\n- **Conflicts (409):** don't retry — surface the typed error, invalidate, and let the user re-decide on fresh data.\n\n```ts\nuseMutation({\n  retry: (count, error: ApiError) => error.isNetworkError && count \u003C 2, \u002F\u002F network-only, bounded\n});\n```\n\n---\n\n## 7. Library adapters\n\nThe five-beat lifecycle is the same; the hooks differ.\n\n| Library            | Optimistic mechanism                                                                                                                                       |\n| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| **TanStack Query** | `onMutate` (cancel + snapshot + patch) → `onError` (rollback) → `onSettled` (invalidate). The reference shape above.                                       |\n| **RTK Query**      | `onQueryStarted`: `updateQueryData` returns a `patchResult`; `await queryFulfilled` and call `patchResult.undo()` in `catch`. `invalidatesTags` on settle. |\n| **SWR**            | `mutate(key, optimisticData, { rollbackOnError: true, populateCache, revalidate: true })` — optimistic data + automatic rollback + revalidate.             |\n\nFor **React Native**, all three libraries work unchanged; the cache is the source of truth on\nnative too. Keep mutation hooks DOM-free so they're shareable across web and native.\n\n---\n\n## 8. Conventions checklist (enforce in review)\n\n- [ ] Optimistic mutations follow cancel → snapshot → patch → rollback → invalidate.\n- [ ] `onMutate` cancels in-flight queries before patching.\n- [ ] Rollback restores the **exact** snapshot from context, not a re-derivation.\n- [ ] Detail **and** every affected list page are patched and snapshotted together.\n- [ ] `onSettled` invalidates so server-computed fields are refetched (on success _and_ error).\n- [ ] Idempotency key is generated at intent time and replayed across retries, not regenerated per attempt.\n- [ ] Money-moving \u002F destructive writes confirm first and disable the trigger while pending.\n- [ ] Non-idempotent writes don't auto-retry; 409s surface rather than retry.\n- [ ] Server state stays in the query cache — never copied into a client store.\n- [ ] Query keys come from a hierarchical factory; invalidation is scoped, not global-blunt.\n\n---\n\n## 9. How to apply this skill\n\n**Adding an optimistic mutation:** decide it's safe to be optimistic (§1). Write the five beats\n(§2). Identify every cache the entity lives in and patch\u002Fsnapshot all of them (§4).\n\n**Making a write safe to retry:** generate an idempotency key at form init, thread it through the\nmutation, confirm the client sends it (§5), and set a network-only bounded retry (§6).\n\n**Debugging a flicker \u002F wrong-state-after-write:** check that `onMutate` cancels queries (late\nrefetch clobber) and that `onSettled` invalidates (stale server-computed fields). Check that _all_\nlist pages were patched, not just the visible one.\n\n**Reviewing the write path:** run the checklist in §8. The highest-value catches are missing\n`cancelQueries` (race clobber), partial cache patches (detail\u002Flist disagreement), and idempotency\nkeys generated inside `mutationFn` (no longer protect retries).\n\n---\n\n## Publishing \u002F installing this skill\n\nThis skill follows the Anthropic `SKILL.md` format and is portable across agents.\n\n1. Keep it under `skills\u002Ffrontend-optimistic-mutations\u002FSKILL.md` in a public GitHub repo.\n2. Keep the frontmatter `name` and high-signal `description` — discovery indexes match against it.\n3. Install with: `npx skills add \u003Corg>\u002F\u003Crepo> --skill \"frontend-optimistic-mutations\"`.\n4. Non-`SKILL.md` agents can be pointed here from `AGENTS.md` \u002F `CLAUDE.md`; Kiro can mirror it as a steering file.\n\n## Limitations\n\n- Use this skill only when the task clearly matches its upstream source and local project context.\n- Verify commands, generated code, dependencies, credentials, and external service behavior before applying changes.\n- Do not treat examples as a substitute for environment-specific tests, security review, or user approval for destructive or costly actions.\n",{"name":5,"risk":24,"source":25,"license":15,"date_added":26,"description":7,"source_repo":27,"source_type":28,"license_source":29},"critical","https:\u002F\u002Fgithub.com\u002Fstareezy-1\u002Ffrontend-architecture-skill\u002Ftree\u002Fmain\u002Fskills\u002Ffrontend-optimistic-mutations",1782864000000,"stareezy-1\u002Ffrontend-architecture-skill","community","https:\u002F\u002Fgithub.com\u002Fstareezy-1\u002Ffrontend-architecture-skill\u002Fblob\u002Fmain\u002FLICENSE","main","a4404a75dc81d6b7e58c5906b6aaffbcb5e84747","Claude\u002Fantigravity skills\u002Fagentic-awesome-skills\u002Fskills\u002Ffrontend-optimistic-mutations",0,"https:\u002F\u002Fgithub.com\u002FMHassan0000\u002FSkills","https:\u002F\u002Fgithub.com\u002FMHassan0000","https:\u002F\u002Fhassanyousaf.vercel.app","Full Stack Developer building web apps, SaaS, AI systems, and automations. Passionate about clean code, UI\u002FUX, backend systems, and turning ideas into products.","2026-08-07 20:42:05",{"source":8,"skillName":5,"commands":40,"prompt":50,"zipAvailable":51},[41,44,47],{"tool":42,"command":43},"npx","npx skills add MHassan0000\u002FSkills --skill frontend-optimistic-mutations",{"tool":45,"command":46},"bunx","bunx skills add MHassan0000\u002FSkills --skill frontend-optimistic-mutations",{"tool":48,"command":49},"pnpm","pnpm dlx skills add MHassan0000\u002FSkills --skill frontend-optimistic-mutations","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FMHassan0000\u002FSkills\u002Fblob\u002Fmain\u002FClaude\u002Fantigravity skills\u002Fagentic-awesome-skills\u002Fskills\u002Ffrontend-optimistic-mutations\u002FSKILL.md",true,[],[54,61,68,75,84,92],{"skillNo":55,"name":56,"nameZh":6,"description":57,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":58,"categories":59,"keywords":60,"publishedAt":19},"01M7AGBX58S04DX8DKKME8N311","vercel-react-best-practices","React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React\u002FNext.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.","https:\u002F\u002Fgithub.com\u002FMHassan0000\u002FSkills\u002Fblob\u002Fmain\u002FClaude\u002Fskills boraztunc github\u002Fvercel-react-best-practices\u002FSKILL.md",[],[],{"skillNo":62,"name":63,"nameZh":6,"description":64,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":19},"01M7AGBREE890608Z7YDMAKH27","stop-slop","Remove AI writing patterns from prose. Use when drafting, editing, or reviewing text to eliminate predictable AI tells and produce more human-like writing.","https:\u002F\u002Fgithub.com\u002FMHassan0000\u002FSkills\u002Fblob\u002Fmain\u002FClaude\u002Fskills boraztunc github\u002Fstop-slop\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":19},"01M7AGAS972A2AN7Q5EW8HEAXK","ogilvy-copywriting","Apply David Ogilvy's advertising principles when writing or reviewing copy, headlines, product descriptions, landing pages, ads, emails, or any persuasive text. Use when the goal is copy that sells, not copy that wins awards. Covers positioning, headlines, promises, brand voice, long-form copy, and visual logic. Source: How to Create Advertising That Sells (1972) + Ogilvy on Advertising.","https:\u002F\u002Fgithub.com\u002FMHassan0000\u002FSkills\u002Fblob\u002Fmain\u002FClaude\u002Fskills boraztunc github\u002Fogilvy\u002FSKILL.md",[],[],{"skillNo":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":79,"licenseFileUrl":80,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":19},"01M7AGAF12803G5JPVMK79AYJB","frontend-design","Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, artifacts, posters, or applications (examples include websites, landing pages, dashboards, React components, HTML\u002FCSS layouts, or when styling\u002Fbeautifying any web UI). Generates creative, polished code and UI design that avoids generic AI aesthetics.","Apache-2.0","https:\u002F\u002Fgithub.com\u002FMHassan0000\u002FSkills\u002Fblob\u002Fmain\u002FClaude\u002Fskills boraztunc github\u002Ffrontend-design\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FMHassan0000\u002FSkills\u002Fblob\u002Fmain\u002FClaude\u002Fskills boraztunc github\u002Ffrontend-design\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":79,"licenseFileUrl":88,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":19},"01M7AG88WWVWCGJY9WA9CH7EY4","webapp-testing","Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.","https:\u002F\u002Fgithub.com\u002FMHassan0000\u002FSkills\u002Fblob\u002Fmain\u002FClaude\u002Fobra superpower skills\u002Fwebapp-testing\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FMHassan0000\u002FSkills\u002Fblob\u002Fmain\u002FClaude\u002Fobra superpower skills\u002Fwebapp-testing\u002FSKILL.md",[],[],{"skillNo":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":79,"licenseFileUrl":96,"sourceHtmlUrl":97,"categories":98,"keywords":99,"publishedAt":19},"01M7AG7ZTNV7XQCWDQ9674FBYB","web-artifacts-builder","Suite of tools for creating elaborate, multi-component claude.ai HTML artifacts using modern frontend web technologies (React, Tailwind CSS, shadcn\u002Fui). Use for complex artifacts requiring state management, routing, or shadcn\u002Fui components - not for simple single-file HTML\u002FJSX artifacts.","https:\u002F\u002Fgithub.com\u002FMHassan0000\u002FSkills\u002Fblob\u002Fmain\u002FClaude\u002Fobra superpower skills\u002Fweb-artifacts-builder\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FMHassan0000\u002FSkills\u002Fblob\u002Fmain\u002FClaude\u002Fobra superpower skills\u002Fweb-artifacts-builder\u002FSKILL.md",[],[]]