Skip to content
Back to skills

Redux Rtk Optimistic

ASecurity

> Apply optimistic and pessimistic cache updates with onQueryStarted for instant UI feedback with automatic rollback

  • 20 stars
  • 0 votes
  • 0 copies
  • 1 view
  • Added September 11, 2026
businesstypescriptapi

Works with

  • api

Security analysis

A100/100

Pro scans all 2 files and shows the line behind each finding

Scanned September 11, 2026

npx -y skills add Intense-Visions/harness-engineering --skill redux-rtk-optimistic --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Redux Rtk Optimistic?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Redux Rtk Optimistic
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/intense-visions-redux-rtk-optimistic/badge)](https://www.skillsdirectory.com/skills/intense-visions-redux-rtk-optimistic)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
# RTK Query Optimistic Updates

> Apply optimistic and pessimistic cache updates with onQueryStarted for instant UI feedback with automatic rollback

## When to Use

- Toggling a like/favorite and wanting instant UI response
- Reordering items in a list via drag-and-drop
- Editing inline fields where waiting for the server feels sluggish
- Any mutation where the expected server response is predictable

## Instructions

1. Use `onQueryStarted` in the mutation endpoint to perform cache updates before or after the server responds.
2. For **optimistic updates**: call `dispatch(api.util.updateQueryData(...))` immediately inside `onQueryStarted`, before awaiting the result. Save the return value — it contains an `undo` function.
3. Wrap the `await queryFulfilled` in try/catch. On failure, call `patchResult.undo()` to revert the optimistic change.
4. For **pessimistic updates**: `await queryFulfilled` first, then update the cache with the server's response.
5. Always match the exact cache key arguments when calling `updateQueryData` — a mismatch silently does nothing.
6. Prefer optimistic updates for idempotent operations (toggles, edits). Prefer pessimistic updates when the server assigns critical data (IDs, computed fields).

```typescript
// Optimistic update — toggle a todo's completed status
toggleTodo: builder.mutation<Todo, { id: string; completed: boolean }>({
  query: ({ id, completed }) => ({
    url: `/todos/${id}`,
    method: 'PATCH',
    body: { completed },
  }),
  async onQueryStarted({ id, completed }, { dispatch, queryFulfilled }) {
    // Optimistically update the cache immediately
    const patchResult = dispatch(
      api.util.updateQueryData('getTodos', undefined, (draft) => {
        const todo = draft.find((t) => t.id === id);
        if (todo) todo.completed = completed;
      })
    );
    try {
      await queryFulfilled;
    } catch {
      // Revert on failure
      patchResult.undo();
    }
  },
}),
```

```typescript
// Pessimistic update — server assigns the ID
createTodo: builder.mutation<Todo, { title: string }>({
  query: (body) => ({ url: '/todos', method: 'POST', body }),
  async onQueryStarted(_, { dispatch, queryFulfilled }) {
    try {
      const { data: newTodo } = await queryFulfilled;
      // Update cache with server response
      dispatch(
        api.util.updateQueryData('getTodos', undefined, (draft) => {
          draft.push(newTodo);
        })
      );
    } catch {
      // No cache to revert — the mutation failed before we touched it
    }
  },
}),
```

## Details

**updateQueryData arguments:** `updateQueryData(endpointName, queryArg, updateFn)`. The `queryArg` must exactly match what was passed to the query hook. If the query was called with `useGetTodosQuery(undefined)`, pass `undefined`. If called with `useGetTodosQuery({ filter: 'active' })`, pass `{ filter: 'active' }`.

**Combining with invalidation:** You can use optimistic updates AND `invalidatesTags` together. The optimistic update gives instant feedback, and the invalidation ensures the cache is eventually consistent with the server.

**Multiple cache entries:** If the same data appears in multiple queries (a list query and a detail query), update both:

```typescript
async onQueryStarted({ id, title }, { dispatch, queryFulfilled }) {
  const patchList = dispatch(api.util.updateQueryData('getPosts', undefined, (draft) => {
    const post = draft.find((p) => p.id === id);
    if (post) post.title = title;
  }));
  const patchDetail = dispatch(api.util.updateQueryData('getPost', id, (draft) => {
    draft.title = title;
  }));
  try {
    await queryFulfilled;
  } catch {
    patchList.undo();
    patchDetail.undo();
  }
},
```

**Anti-patterns:**

- Forgetting to `undo()` on failure — leaves the UI in a stale state
- Mismatched query args — the update silently does nothing
- Optimistic updates for operations with unpredictable server behavior (payments, inventory)

## Source

https://redux-toolkit.js.org/rtk-query/usage/manual-cache-updates

## Process

1. Read the instructions and examples in this document.
2. Apply the patterns to your implementation, adapting to your specific context.
3. Verify your implementation against the details and edge cases listed above.

## Harness Integration

- **Type:** knowledge — this skill is a reference document, not a procedural workflow.
- **No tools or state** — consumed as context by other skills and agents.

## Success Criteria

- The patterns described in this document are applied correctly in the implementation.
- Edge cases and anti-patterns listed in this document are avoided.

Files in this skill

  • SKILL.md4.5 KB
  • skill.yaml751 B

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.