T
TanStack8mo ago
rare-sapphire

Drawbacks of multiple related mutations in one hook?

is grouping related mutations in one hook bad?
const useFolderMutations = () => {
const queryClient = useQueryClient()
const create = useMutation({
mutationFn: createFolder,
onSuccess: () => {...invalidate stuff},
onError: () => {...}
});
const delete = useMutation({
mutationFn: deleteFolder,
onSuccess: () => {...invalidate stuff},
onError: () => {...}
});

return {create, remove}
}
const useFolderMutations = () => {
const queryClient = useQueryClient()
const create = useMutation({
mutationFn: createFolder,
onSuccess: () => {...invalidate stuff},
onError: () => {...}
});
const delete = useMutation({
mutationFn: deleteFolder,
onSuccess: () => {...invalidate stuff},
onError: () => {...}
});

return {create, remove}
}
And I let's say I use them in different components:
// in DeleteFolderForm.tsx
const remove = useFolderMutations().remove

const handleRemove = (id: string) => remove.mutate(id)
// in DeleteFolderForm.tsx
const remove = useFolderMutations().remove

const handleRemove = (id: string) => remove.mutate(id)
// in CreateFolderForm.tsx
const create = useFolderMutations().create

const handleCreate = (name: string) => create.mutate(name)
// in CreateFolderForm.tsx
const create = useFolderMutations().create

const handleCreate = (name: string) => create.mutate(name)
2 Replies
continuing-cyan
continuing-cyan8mo ago
Hi, it's not necessarily bad, but it has drawbacks. You can not export these mutations separately, it means that if you need only a create mutation you are still going to export them both so you waste memory and computation to instantiate mutation you will not use in this component. It also means that tree shaking won't work with this approach. You can write these mutations as a separate fn and export them individually. This will give you more flexibility. Your file should be a thing that groups your mutations and manages how you import/export stuff.
rare-sapphire
rare-sapphireOP8mo ago
Oh yeah. Exporting them exposes all the other properties. Separating them is definitely better than my current set-up. Thank you!!

Did you find this page helpful?