T
TanStack3y ago
fair-rose

mutationFn needs access to a hook

I'm a huge fan of Dominik's post "Leveraging the Query Function Context" (https://tkdodo.eu/blog/leveraging-the-query-function-context) (well, and all of the other ones). I really enjoy defining the query functions separately from the hook as shown in the post. However, when the queryFn or mutationFn depends on another hook, I've had to inline the functions as below:
export const myCustomHook = () => {
const otherHook = useOtherHook();

return useMutation({
mutationFn: () => {
return otherHook.somePromiseThing();
}
})
}
export const myCustomHook = () => {
const otherHook = useOtherHook();

return useMutation({
mutationFn: () => {
return otherHook.somePromiseThing();
}
})
}
I feel like this pattern sucks and I'm not sure if it's because I am abusing hooks or overlooking an obvious alternative. Can anyone weigh in? Thanks
1 Reply
rival-black
rival-black3y ago
It is fine. E.g., after a mutation runs you often want to invalidate some queries and therefore need to call useQueryClient. This pattern is pretty standard in react: compose a new hook out of other hooks.

Did you find this page helpful?