Is it bad practice to use useMutation or useQuery inside a service class (React Query + TypeScript)?
I’ve built an authentication flow using React Query and TypeScript, and everything works fine.
But I’m not sure if calling useMutation() inside a service class is considered a bad practice, instead of defining it directly inside the React component.
Does this approach break any React rules ?
Or is it acceptable as long as the service function is called from inside a React component?
Thanks guys

6 Replies
continuing-cyan•3w ago
it will definitely break if someone calls
authService.signup outside of a react component; the linter should also warn you here
authService should just be a custom useAuthService hookharsh-harlequinOP•3w ago
Yes, exactly. But if it’s never called anywhere outside of a React component, would that cause any problem?

harsh-harlequinOP•3w ago
Because if I use an alias, I won’t get a linter error anymore. (rules of hook)
My question is really about how it works. Does it break anything?
Sorry for insisting

harsh-harlequinOP•3w ago
No matter what you answer, I’m going to use a custom hook, but it’s really just to understand.
continuing-cyan•3w ago
I mean at this point you're just asking me how react works I guess 😅
do this in classes and only call them in components and it will work at runtime, because react needs the same hooks being called during render. how you achieve that doesn't matter, but the
use... convention + linters make it so that you can't make mistakes.
if someone adds an early return before your authService.signup call in the component:
your code will break at runtime, because now you're calling hooks conditionally. If it's a real hook call the linter will tell you about it.
please just read the react docs: https://react.dev/reference/rules/rules-of-hooksRules of Hooks – React
The library for web and native user interfaces
harsh-harlequinOP•3w ago
Thank you ^^ 🙂