T
TanStack3w ago
harsh-harlequin

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
No description
6 Replies
continuing-cyan
continuing-cyan3w 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 hook
harsh-harlequin
harsh-harlequinOP3w ago
Yes, exactly. But if it’s never called anywhere outside of a React component, would that cause any problem?
No description
harsh-harlequin
harsh-harlequinOP3w 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
No description
harsh-harlequin
harsh-harlequinOP3w ago
No matter what you answer, I’m going to use a custom hook, but it’s really just to understand.
continuing-cyan
continuing-cyan3w ago
I mean at this point you're just asking me how react works I guess 😅
import { useState as state } from 'react'
import { useState as state } from 'react'
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:
if (!someCondition) return <Navigate to="/login" />
if (!someCondition) return <Navigate to="/login" />
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-hooks
Rules of Hooks – React
The library for web and native user interfaces
harsh-harlequin
harsh-harlequinOP3w ago
Thank you ^^ 🙂

Did you find this page helpful?