# Add Optimistic Updates to a React App

Yes. An agent makes comment create and delete in a React Query app update the list before the server answers, roll back on error, tests both paths and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-optimistic-ui/react/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads how mutations and queries are wired before touching a component. In an app shaped like the `apps/react-vite` application in alan2207/bulletproof-react, `package.json` has `@tanstack/react-query` ^5.32.0, `react` ^18.3.1, `react-router` ^7.0.2, `zod`, `react-hook-form`, `nanoid` ^5.0.7, and for tests `vitest` ^2.1.4, `msw` ^2.2.14, `@mswjs/data` and Testing Library. `src/lib/react-query.ts` sets `staleTime` to a minute and `retry` to `false`, and exports the `MutationConfig` type every API hook takes. `src/features/comments/api/get-comments.ts` builds an infinite query keyed `['comments', discussionId]` whose pages are `{ data: Comment[], meta }`, and `src/types/api.ts` defines `Comment` as an entity with `id`, `createdAt`, `body`, `discussionId` and `author`.

`create-comment.ts` and `delete-comment.ts` each wrap `useMutation` and, in `onSuccess`, call `invalidateQueries` on that key before running the caller's own `onSuccess`. So today a delete shows a spinner on the confirm button in `delete-comment.tsx` until the request returns, then the list refetches; a new comment stays in the `FormDrawer` of `create-comment.tsx` until the server answers. `comments-list.tsx` flattens `pages` and renders each comment with `MDPreview` and a `DeleteComment` button behind the `comment:delete` policy from `src/lib/authorization.tsx`.

The agent changes the two hooks and nothing in the components' markup. `useDeleteComment` gets an `onMutate` that cancels in-flight queries for the key, snapshots the cache with `getQueryData`, and writes the pages back with that comment filtered out with `setQueryData`; `onError` restores the snapshot and raises a notification through `useNotifications`; `onSettled` invalidates, so the server's view wins in the end. `useCreateComment` does the same in the other direction: it inserts a comment with a `nanoid` id, `createdAt` of `Date.now()`, the body from the form and the current user from `useUser` in `src/lib/auth.tsx` as `author` at the top of the first page, and on success replaces the placeholder with the comment the server returned. The hooks keep wrapping the caller's `onSuccess` the way they do now, so `create-comment.tsx` and `delete-comment.tsx` still close their drawer and dialog and still show their success notifications.

Tests follow `src/app/routes/app/discussions/__tests__/discussion.test.tsx`, which renders a route with `renderApp`, `createUser` and `createDiscussion` from `src/testing/test-utils.tsx` against the MSW handlers in `src/testing/mocks/handlers/comments.ts`. The agent adds a test that deletes a comment and asserts it leaves the list before the mocked request's `networkDelay` elapses, one that overrides the delete handler to answer an error and asserts the comment comes back with an error notification, and one for a created comment appearing at once with the signed-in user's name. Before pushing it runs what `.github/workflows/react-vite-ci.yml` runs from `apps/react-vite`: `yarn test`, `yarn lint`, `yarn check-types` and `yarn build`.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add optimistic updates to comment creation and deletion in the React app in apps/react-vite and open a pull request. Read package.json, src/lib/react-query.ts, src/types/api.ts, src/lib/auth.tsx, src/features/comments/api/get-comments.ts, create-comment.ts and delete-comment.ts, src/features/comments/components/comments-list.tsx, create-comment.tsx and delete-comment.tsx, src/testing/test-utils.tsx, src/testing/mocks/handlers/comments.ts and src/app/routes/app/discussions/__tests__/discussion.test.tsx first. In useDeleteComment add onMutate that cancels queries for the comments key, snapshots the infinite query data and removes the comment from every page with setQueryData; restore the snapshot and add an error notification in onError; invalidate in onSettled. In useCreateComment insert a placeholder comment with a nanoid id, Date.now() as createdAt and the current user as author at the top of the first page, and swap it for the server's comment on success. Keep both hooks wrapping the caller's onSuccess as they do now so the drawer, dialog and success notifications still work; do not change component markup. Add tests beside discussion.test.tsx: a delete that disappears before the mocked request resolves, a failed delete that restores the comment and shows the error notification, and a create that appears at once. From apps/react-vite run yarn test, yarn lint, yarn check-types and yarn build, and put their output in the pull request.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request that changes `src/features/comments/api/create-comment.ts` and `delete-comment.ts` and adds one test file beside `discussion.test.tsx`. The description lists the three new tests with the `vitest` output, the `eslint` and `tsc` results, and a short note on the ordering choice: `onSettled` always invalidates, so a stale placeholder cannot outlive the next refetch.

On a repository with this `React Vite CI` workflow, the pull request runs install, build, test, lint and type check from `apps/react-vite`, then the Playwright suite against the mock server. The e2e specs read the page after the request resolves, so they pass unchanged.

A reviewer checks that the placeholder comment passes the `comment:delete` policy check in `comments-list.tsx`, since its `author` is the signed-in user, that the rollback restores every page and not only the first, and that a mutation fired while the list is still loading does not write into an empty cache. Then they decide whether discussions deserve the same treatment, which the pull request leaves for a follow-up.

## Run it on every new mutation hook

The same request works for any feature folder in the app. Send one `POST /o/{org}/sessions` per feature, naming the hook files in `input`, and each run reads that feature's query key and page shape before writing `onMutate`, so discussions, whose list is a plain paginated query rather than an infinite one, get a different cache update than comments.

Give the API key a `webhook_url` and each run POSTs `run.completed` when its turn finishes, with the `session_url` to read the pull request from, so a handler on your server can open the review where that feature's owners look.

## Why run it on Rush?

Optimistic updates are easy to demo and hard to get right: the bug is in the error path, which nobody clicks through by hand. The agent runs the app's own MSW mock server and the Vitest suite in its sandbox, overrides a handler to fail, and keeps the test output in the run's record, so the pull request shows the rollback working rather than describing it.

The repository already has a CI job that runs build, test, lint and type check from `apps/react-vite`, and the agent runs the same four commands before pushing. That means the review starts from a green pull request, and the same request body applies to any React Query app a team maintains.

## Frequently asked questions

### Will the placeholder comment flicker when the server answers?

No. On success the hook swaps the placeholder for the server's comment by id inside the cached page, and `onSettled` then invalidates so a refetch confirms the list. The item keeps its position, and only `createdAt` and `id` change under it.

### Does this change the notifications?

The success notifications in `create-comment.tsx` and `delete-comment.tsx` stay where they are. The hooks add one error notification through `useNotifications` on rollback, with the message from the failed request.

### What about the infinite query's pages?

The cache for `['comments', discussionId]` is `{ pages, pageParams }`. The delete update maps over every page's `data`, and the create update writes into the first page only, keeping `meta` as it was. The tests render a discussion with more than one page of comments to cover both.

### Does it touch the Next.js apps in the same repository?

No. The prompt names `apps/react-vite`, and the pull request stays inside it. The `nextjs-app` and `nextjs-pages` applications have their own comment hooks and their own CI workflows, and a second run with their paths in `input` does the same job there.

## More React jobs

- [Convert React Class Components to Hooks](https://getrush.ai/run/convert-class-components-to-hooks/react/)
- [Debug a Front-End Bug in a React App Together](https://getrush.ai/run/debug-together-in-browser/react/)
- [Find Dead Code in a React Project](https://getrush.ai/run/find-dead-code/react/)

## The same job on other stacks

- [Add Optimistic UI to a React Router Form from a Linear Issue](https://getrush.ai/run/add-optimistic-ui/react-router/)
- [Add Optimistic Updates to a TanStack Query App](https://getrush.ai/run/add-optimistic-ui/tanstack-query/)
- [Add Optimistic Updates to a tRPC and Next.js App](https://getrush.ai/run/add-optimistic-ui/trpc/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
