SWR Mutations with useSWRMutation
You'll learn how SWR handles POST, PUT, and DELETE operations with its dedicated mutation hook and how it differs from TanStack Query's approach.
What is useSWRMutation?
While useSWR focuses on GET requests with automatic revalidation, useSWRMutation handles operations that change server data—creating, updating, or deleting records. Think of it as SWR's answer to TanStack Query's useMutation, but with a lighter, more manual touch.
The Core API
import useSWRMutation from 'swr/mutation'
async function createUser(url, { arg }) {
return fetch(url, {
method: 'POST',
body: JSON.stringify(arg)
}).then(r => r.json())
}
function CreateUserForm() {
const { trigger, isMutating } = useSWRMutation('/api/users', createUser)
const handleSubmit = async (userData) => {
await trigger(userData) // Pass data to mutation
}
return <button disabled={isMutating}>Create User</button>
}
Unlike useMutation which auto-fires or uses a mutate function, useSWRMutation gives you a trigger function—you call it explicitly when ready.
Key Differences from TanStack Query
SWR's approach is more manual: there's no built-in onSuccess callback pattern or automatic query invalidation. You typically handle cache updates yourself using mutate() from useSWR separately, or rely on revalidation strategies to refresh data naturally.
TanStack Query is more batteries-included: callbacks, automatic invalidation, and optimistic updates are baked into useMutation. SWR keeps it minimal—you wire up what you need.
Key Takeaway: useSWRMutation provides a lightweight trigger-based mutation system that pairs with SWR's philosophy of simplicity, but requires more manual cache coordination compared to TanStack Query's useMutation.