Saltar al contenido
Skillpedia
Sitios e interfaces (frontend)48 mil · #4671

frontend-optimistic-mutations

Qué hace

Esta skill te ayuda a que los cambios en pantalla se sientan instantáneos para el usuario. Actualiza la interfaz de inmediato y, si algo sale mal, deshace el cambio sin dejar rastro.

Cuándo usarla

  • ✓Al marcar un elemento como completado.
  • ✓Al cambiar el estado de un pedido.
  • ✓Al reordenar una lista de elementos.

Link de la skill

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

Cópialo y pégalo en tu IA (Claude, ChatGPT o Cursor) pidiéndole que siga las instrucciones.

Cómo usar

La forma más fácil: copia el mensaje y pégalo en tu IA. Ella lee la skill y sigue las instrucciones.

Mensaje listo para pegar

Usa esta skill para ayudarme: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/frontend-optimistic-mutations/SKILL.md Lee el archivo SKILL.md de ese link y sigue sus instrucciones en mi tarea.
¿Quieres que tu IA encuentre skills como esta por sí sola?Instala el MCP gratis de Skillpedia: una línea, y busca entre 15.000+ skills antes de cada tarea.Instalar en 1 minuto →

Ejemplo de qué pedirle a la IA

“Haz que marcar una factura como 'pagada' se sienta instantáneo, pero revierte el cambio si hay un error.”

5 skills nuevas por semana. 1 minuto de lectura.

Cómo funciona

Cuando haces un cambio, la pantalla se actualiza enseguida. Si el cambio no llega al servidor, la pantalla vuelve a su estado anterior como si nada hubiera pasado.

Contenido técnico (SKILL.md original)

Texto original del autor, en inglés, directo de 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);

…
Preguntas frecuentes

¿Qué significa 'actualización optimista'?

Es cuando la interfaz de usuario se actualiza de inmediato para reflejar un cambio, incluso antes de que el servidor confirme que el cambio se realizó con éxito. Es como rellenar un formulario y ver aparecer 'guardado' antes de que el sistema lo guarde realmente.

¿Qué es el 'rollback'?

Es la capacidad de revertir un cambio al estado exacto en el que estaba antes, en caso de error. Así se evita que el usuario se quede con un estado inconsistente o incorrecto.

¿Por qué es importante que las listas y los detalles coincidan?

Para asegurar que la información sea coherente en toda la aplicación. Si marcas un elemento como pagado en una lista, todos los demás lugares donde aparece ese elemento (como la página de detalle) también deben reflejar ese cambio de inmediato.

Detalles

Descripción original del autor

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

Popularidad

Estrellas en GitHub
48 mil
Posición en el ranking
#4671
Licencia
MIT
Actualizada
15/10/2026

¿Te sirve esta skill?

0

Entra para votar.

Comentarios

  • …

Más skills de este repositorio

Skills parecidas