Update & Delete Mutations in React

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

Update & Delete Mutations

Implementing update and delete operations

typescript
// Update mutation
function EditPost({ post }) {
  const queryClient = useQueryClient()

  const updateMutation = useMutation({
    mutationFn: ({ id, ...data }) => updatePost(id, data),
    onSuccess: (data) => {
      // Update specific item in cache
      queryClient.setQueryData(['post', data.id], data)
      // Invalidate list
      queryClient.invalidateQueries({ queryKey: ['posts'] })
    }
  })

  const deleteMutation = useMutation({
    mutationFn: deletePost,
    onSuccess: (_, postId) => {
      // Remove from cache
      queryClient.removeQueries({ queryKey: ['post', postId] })
      queryClient.invalidateQueries({ queryKey: ['posts'] })
    }
  })

  return (
    <div>
      <button onClick={() => updateMutation.mutate({
        id: post.id,
        title: 'Updated Title'
      })}>
        Update
      </button>
      <button onClick={() => deleteMutation.mutate(post.id)}>
        Delete
      </button>
    </div>
  )
}
💡 Update specific cache entries with setQueryData
⚡ Optimistic deletes provide instant feedback
📌 Always provide rollback logic in onError
🟢 Use removeQueries to clean up deleted item caches
mutationsupdatedeletecrud

More React tasks

Back to the full TanStack Query cheat sheet