React
/Advanced
Mutations (React Query)
Definition
In TanStack Query, a Mutation is used to create/update/delete data (POST, PUT, DELETE), whereas a Query is used to read data (GET).
Explain Like I'm New
If a Query is asking the librarian for a book to read, a Mutation is handing the librarian a brand new book to add to the shelf. Because the shelf has changed, you need to tell the librarian to update their catalog (Query Invalidation).
Real World Example
When a user submits a "Create Post" form, you use `useMutation()`. On success, you tell TanStack Query to invalidate the `["posts"]` query key. TanStack Query will automatically trigger a background fetch for the new list of posts, updating the UI seamlessly.
Common Use Cases
- •Submitting forms
- •Liking a post or deleting an item
- •Tracking the loading state of a POST request
Interactive Example
Loading Code Playground...
Interview Questions
basic
- What is the difference between `useQuery` and `useMutation`?
- Does a mutation run automatically when the component mounts?
intermediate
- How do you trigger a mutation?
- What does `queryClient.invalidateQueries` do?
advanced
- What is the difference between `mutate` and `mutateAsync`?
- How do you implement an Optimistic Update during a mutation?
trick
- If a mutation fails, does it automatically retry like a query does?