function
function7mo 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
artistrea5mo ago
It's a bit late, but This is not related to trpc, the example is an example using react query
function
functionOP5mo ago
xD
artistrea
artistrea5mo 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
function
functionOP5mo 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
artistrea5mo 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
function
functionOP5mo 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
artistrea5mo ago
I mean just now I opened the docs you linked*
artistrea
artistrea5mo ago
No description
artistrea
artistrea5mo ago
I didn't think that would be there lol
function
functionOP5mo ago
oh

Did you find this page helpful?