Basic Mutations in React

From the TanStack Query cheat sheet · Mutations · verified Jul 2026

Basic Mutations

Using useMutation for data modifications

typescript
import { useMutation, useQueryClient } from '@tanstack/react-query'

function CreatePost() {
  const queryClient = useQueryClient()

  const mutation = useMutation({
    mutationFn: createPost,
    onSuccess: () => {
      // Invalidate and refetch
      queryClient.invalidateQueries({ queryKey: ['posts'] })
    },
  })

  return (
    <form
      onSubmit={(e) => {
        e.preventDefault()
        const formData = new FormData(e.target)
        mutation.mutate({
          title: formData.get('title'),
          content: formData.get('content')
        })
      }}
    >
      <input name="title" />
      <textarea name="content" />
      <button type="submit">
        {mutation.isPending ? 'Creating...' : 'Create Post'}
      </button>
      {mutation.isError && (
        <div>Error: {mutation.error.message}</div>
      )}
    </form>
  )
}
💡 onMutate enables optimistic updates for instant UI feedback
⚡ mutateAsync returns a promise for async/await usage
📌 Always invalidate related queries after mutations
🟢 Use mutate for fire-and-forget, mutateAsync when you need the result
mutationscreateoptimistic

Continue with TanStack Query

Save the full cheat sheet or work through every related task.

More React tasks

Back to the full TanStack Query cheat sheet