React Query: Using callbacks on useMutation vs mutate itself
18 January 2023 (Updated 21 January 2023)
In a nutshell
- Callbacks on
useMutate
fire before the callbacks onmutate
. - Callbacks on
mutate
might not fire if the component callingmutate
unmounts before the mutation has finished.
When to use useMutation callbacks
For things that are absolutely necessary and logic-related (e.g., query invalidation).
When to use .mutate callbacks
For UI-related things (e.g., redirects or showing toast notifications).
const useUpdateTodo = () =>
useMutation({
mutationFn: updateTodo,
// ✅ always invalidate the todo list
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['todos', 'list'] })
},
})
// in the component
const updateTodo = useUpdateTodo()
updateTodo.mutate(
{ title: 'newTitle' },
// ✅ only redirect if we're still on the detail page
// when the mutation finishes
{ onSuccess: () => history.push('/todos') }
)
Sources
Tagged:
React Query
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment