funki
funki4mo ago

Why are `new QueryClient` and `trpc.createClient` run inside a component in the React setup?

From https://trpc.io/docs/client/react/setup:
function App() {
const [queryClient] = useState(() => new QueryClient());
const [trpcClient] = useState(() =>
trpc.createClient({ ... }),
);
// ...
function App() {
const [queryClient] = useState(() => new QueryClient());
const [trpcClient] = useState(() =>
trpc.createClient({ ... }),
);
// ...
if these two are "made stable" through useState() and since they should exist only once per SPA (like a singleton), why not just put them outside the component? is this related to HMR?
10 Replies
artistrea
artistrea3mo ago
It's a bit late, but This is not related to trpc, the example is an example using react query
funki
funki3mo ago
xD
artistrea
artistrea3mo ago
The reason is ssr Basically, the query client is stateful It stores the api calls in cache You don't want it to share cache between different requests, which can be from different users
funki
funki3mo ago
hmm SSR 🤔 i think i understand i guess you could theoretically disable caching on the server? i mean, this makes sense, but the reason behind it is not obvious at all and some dev might do the mistake of having a global instance with SSR.
artistrea
artistrea3mo ago
I agree And you could But I think the requests also wouldn't be deduped on the server as well Not sure about this though
funki
funki3mo ago
yeah, probably. kind of a tough issue to solve in a way that's opaque to devs. ideally you'd want the the recommended setup to be secure and expressive on why it's made that way.
artistrea
artistrea3mo ago
I mean just now I opened the docs you linked*
artistrea
artistrea3mo ago
No description
artistrea
artistrea3mo ago
I didn't think that would be there lol
funki
funki3mo ago
oh