본문으로 건너뛰기
Skillpedia
웹사이트 및 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가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/frontend-optimistic-mutations/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 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

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬