tanstack-mutations-and-invalidation
Skill10 starsChanged 6 months agoMITView on GitHub
Use when writing TanStack Query mutations: useMutation, onSuccess invalidation, optimistic updates, error rollback, or chained mutations. Not for read-only queries (use tanstack-query-alternative).
In this repository56 other files it gives its agents.
- accessibility-passSkill
- analytics-eventsSkill
- api-error-handlingSkill
- audit-logging-backendSkill
- background-jobs-and-cronSkill
- dark-mode-and-themingSkill
- dashboard-charts-rechartsSkill
- edge-functions-and-webhooksSkill
- email-and-notificationsSkill
- error-states-and-empty-uiSkill
- feature-flags-and-togglesSkill
- file-upload-storageSkill
- i18n-multi-languageSkill
- lovable-prompting-playbookSkill
- lovable-ship-checklistSkill
- migration-playbookSkill
- multi-tenant-backendSkill
- onboarding-copySkill
- optimistic-updatesSkill
- payment-failed-and-recoverySkill
- payment-webhook-idempotencySkill
- payment-webhook-testingSkill
- performance-budgetSkill
- pg-cron-recipesSkill
- pg-cron-scheduled-jobsSkill
- pg-cron-with-pg-net-edgeSkill
- postgres-full-text-searchSkill
- postgres-triggers-and-functionsSkill
- pricing-and-billingSkill
- programmatic-seo-content-qualitySkill
- programmatic-seo-pagesSkill
- rate-limiting-edgeSkill
- realtime-and-subscriptionsSkill
- refactor-safe-diffSkill
- release-notesSkill
- seo-core-web-vitalsSkill
- seo-landing-pageSkill
- seo-meta-tags-spaSkill
- seo-sitemap-generationSkill
- seo-ssr-and-prerenderingSkill
- seo-structured-dataSkill
- server-input-validationSkill
- shadcn-patternsSkill
- soft-delete-and-archivingSkill
- stripe-one-time-payment-webhooksSkill
- stripe-payment-webhooksSkill
- supabase-auth-flowsSkill
- supabase-database-designSkill
- supabase-rls-and-authSkill
- support-replySkill
- tanstack-infinite-queriesSkill
- tanstack-prefetch-and-hydrationSkill
- tanstack-query-alternativeSkill
- tanstack-router-data-loadersSkill
- tanstack-start-server-routesSkill
- typed-api-hooks-formsSkill
The file
We split this skill into the rules it gives an agent
4 rules. About 0 are common, 0 are distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 11
Every server write goes through useMutation.
- Very specific: line 42
Use mutateAsync only when you need to await (e.g.
- Very specific: line 106
Always implement onError rollback.
- Very specific: line 133
When you must chain, use mutateAsync and try/catch:
≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
TanStack mutations and invalidation
Every server write goes through useMutation. Treat invalidation as part of the mutation contract, not an afterthought.
Companion skills: tanstack-query-alternative, optimistic-updates, api-error-handling.
Basic mutation
// src/hooks/mutations/useCreateProject.ts
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { createProject } from "@/api/projects";
import { projectKeys } from "../queries/keys";
export function useCreateProject() {
const qc = useQueryClient();
return useMutation({
mutationFn: createProject,
onSuccess: (newProject) => {
qc.invalidateQueries({ queryKey: projectKeys.all });
qc.setQueryData(projectKeys.detail(newProject.id), newProject);
},
});
}Components call it cleanly:
const { mutate, isPending, error } = useCreateProject();
<Button disabled={isPending} onClick={() => mutate(values)}>Create</Button>Use mutateAsync only when you need to await (e.g. inside a form onSubmit).
Invalidation strategies
Pick one per mutation:
| Strategy | When | API |
| Invalidate | Lists may change shape | invalidateQueries({ queryKey }) — marks stale, refetches what's mounted |
| Set data | You already have the new value | setQueryData(key, value) — instant, no refetch |
| Remove | Resource is gone | removeQueries({ queryKey }) |
| Reset | Wipe cache (logout, switch org) | qc.clear() or resetQueries({ queryKey }) |
Combine when both apply: optimistically setQueryData, then invalidateQueries on settle to reconcile.
Broad invalidation by prefix
Key factories sort tuples broadest-first so a single invalidation wipes related queries:
qc.invalidateQueries({ queryKey: projectKeys.all });
// invalidates ["projects"], ["projects", "list", ...], ["projects", "detail", ...]For partial matches, use a predicate:
qc.invalidateQueries({
predicate: (q) => q.queryKey[0] === "projects" && q.queryKey[1] === "list",
});Optimistic updates with rollback
export function useToggleLike(postId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: () => api.toggleLike(postId),
onMutate: async () => {
await qc.cancelQueries({ queryKey: postKeys.detail(postId) });
const prev = qc.getQueryData<Post>(postKeys.detail(postId));
qc.setQueryData<Post>(postKeys.detail(postId), (p) =>
p ? { ...p, liked: !p.liked, like_count: p.like_count + (p.liked ? -1 : 1) } : p,
);
return { prev };
},
onError: (_err, _vars, ctx) => {
if (ctx?.prev) qc.setQueryData(postKeys.detail(postId), ctx.prev);
},
onSettled: () => {
qc.invalidateQueries({ queryKey: postKeys.detail(postId) });
},
});
}Rules:
cancelQueriesbefore writing optimistic data — otherwise in-flight refetches will overwrite it.- Always implement
onErrorrollback. - Reconcile with
onSettledinvalidation; server can change denormalized counts.
See optimistic-updates for the full UX patterns (delete-with-undo, etc.).
Error handling
Mutations should surface errors via the hook return; don't try/catch inside the hook unless you can fully recover.
const { mutate, error, isPending } = useCreateProject();
useEffect(() => {
if (error) toast.error("Could not create project", { description: humanize(error) });
}, [error]);Map server error slugs from api-error-handling to UI copy in a single humanize(error) helper — do not branch on error.message strings.
Sequencing and dependent mutations
For multi-step writes (e.g. create org → create project → invite members), prefer one edge function that does all three atomically and one mutation in the UI. Avoid chained mutate → onSuccess → mutate in the client — partial failures leave inconsistent state.
When you must chain, use mutateAsync and try/catch:
async function onSubmit(values: FormValues) {
try {
const org = await createOrg.mutateAsync(values.org);
await createProject.mutateAsync({ orgId: org.id, ...values.project });
} catch (e) {
toast.error("Setup failed", { description: humanize(e) });
}
}Avoid
- Mutations without an invalidation plan (lists stay stale).
- Optimistic updates without rollback.
- Calling
qc.clear()after small mutations (nukes unrelated caches). - Triggering refetch storms by invalidating with no predicate from inside a high-frequency mutation.
onSuccess: () => window.location.reload()— defeats the cache.
Checklist
- Invalidate or
setQueryDataon every mutation. - Optimistic mutations implement
onErrorrollback andonSettledreconcile. isPendingdisables the trigger.- Errors surfaced via hook return; mapped to UI copy via a single helper.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

