本文へスキップ
Skillpedia
WebサイトとUI(フロントエンド)48k · #4671

frontend-optimistic-mutations

できること

このスキルは、画面上の操作を利用者にとって即座に反映されているように感じさせるのに役立ちます。まず画面をすぐに更新し、もし何か問題が起きた場合は、変更を跡形もなく元に戻します。

使う場面

  • ✓項目を完了済みにマークするとき。
  • ✓注文のステータスを変更するとき。
  • ✓項目のリストの並び順を変更するとき。

スキルのリンク

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/frontend-optimistic-mutations/SKILL.md

コピーしてAI(Claude、ChatGPT、Cursor)に貼り付け、指示に従うよう頼んでください。

使い方

いちばん簡単な方法:メッセージをコピーしてAIに貼り付けるだけ。AIがスキルを読んで指示に従います。

貼り付け用メッセージ

このスキルを使って手伝ってください:https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/frontend-optimistic-mutations/SKILL.md このリンクのSKILL.mdファイルを読んで、私の作業でその指示に従ってください。
こういうスキルを、AIが自分で見つけてくれたら?無料のSkillpedia MCPをインストール。1行で、作業の前に15,000+のスキルから探してくれます。1分でインストール →

AIへの頼み方の例

“請求書を「支払済み」にする操作を即座に反映させてください。ただしエラーが起きた場合は元に戻してください。”

毎週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

  1. The optimistic lifecycle is fixed. cancel → snapshot → patch → (error: roll back) → (settle: invalidate). Every optimistic mutation follows the same five beats.
  2. 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.
  3. 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.
  4. 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.
  5. 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);

…
よくある質問

「楽観的更新」とはどういう意味ですか?

サーバーが変更の成功を確認する前に、ユーザーインターフェースが変更を即座に反映することです。フォームに入力して、システムが実際に保存する前に「保存しました」と表示されるような仕組みです。

「ロールバック」とは何ですか?

エラーが起きた場合に、変更を元の状態に正確に戻す機能のことです。これにより、ユーザーが矛盾した状態や誤った状態のまま取り残されることを防ぎます。

リストと詳細画面の情報を一致させることが重要なのはなぜですか?

アプリ全体で情報の一貫性を保つためです。リストで項目を支払済みにした場合、その項目を表示している他の場所(詳細ページなど)も、すぐに同じ変更を反映する必要があります。

詳細

作者による元の説明

A portable, framework-agnostic discipline for the write path of any React or React Native app using a query/cache layer.

repo: sickn33/agentic-awesome-skills

人気

GitHubのスター
48k
ランキング
#4671
ライセンス
MIT
更新日
2026/10/15

このスキルは役に立ちますか?

0

ログイン して投票しましょう。

コメント

  • …

このリポジトリの他のスキル

似ているスキル