---
name: "tanstack-query-v5-optimistic"
description: "Execute resilient server mutations with instant optimistic cache updates and automatic rollback."
metadata:
  author: "TanStack"
  version: "1.0.0"
  runtime_compatibility:
    - "codex"
    - "claude-code"
    - "cursor"
    - "windsurf"
triggers:
  - "optimistic update tanstack query v5"
  - "cancel queries queryclient"
  - "rollback onmutate react query"
permissions:
  fs_read: true
  fs_write: "workspace"
  shell_exec: false
  net_access: false
---

# TanStack Query v5 Optimistic Updates & Cache Mutations

Implements TanStack Query v5 (React Query): useMutation with onMutate, queryClient.cancelQueries, updating query cache directly with setQueryData, onError rollback contexts, and onSettled invalidation.

## When to Invoke
Invoke this skill whenever you need to:
- optimistic update tanstack query v5
- cancel queries queryclient
- rollback onmutate react query

## Execution SOP & Rules
1. Cancel in-flight queries: await queryClient.cancelQueries({ queryKey: ['todos'] }).
2. Snapshot previous state: const previousTodos = queryClient.getQueryData(['todos']).
3. Optimistically update cache: queryClient.setQueryData(['todos'], old => [...old, newTodo]).
4. In onError: restore snapshot with queryClient.setQueryData(['todos'], context.previousTodos).

## Verification Checklist
- Run local linting, syntax validation, and type-checks before reporting completion.
- Ensure all created or modified files adhere to workspace boundaries and avoid uncommitted secrets.
- Verify tests or build commands exit cleanly with return code 0.
