tRPC React - why the useState hook?

Hey. I've been following the docs for setting up tRPC for a React based project. I noted in the docs that they recommend wrapping the tRPC client into a useState(). Could someone explain why?
11 Replies
domi?
domi?OP3y ago
https://trpc.io/docs/v10/react#3-add-trpc-providers
function App() {
const [queryClient] = useState(() => new QueryClient());
const [trpcClient] = useState(() =>
trpc.createClient({
links: [
httpBatchLink({
url: 'http://localhost:5000/trpc',
// optional
headers() {
return {
authorization: getAuthCookie(),
};
},
}),
],
}),
);
return (
<trpc.Provider client={trpcClient} queryClient={queryClient}>
<QueryClientProvider client={queryClient}>
{/* Your app here */}
</QueryClientProvider>
</trpc.Provider>
);
}
function App() {
const [queryClient] = useState(() => new QueryClient());
const [trpcClient] = useState(() =>
trpc.createClient({
links: [
httpBatchLink({
url: 'http://localhost:5000/trpc',
// optional
headers() {
return {
authorization: getAuthCookie(),
};
},
}),
],
}),
);
return (
<trpc.Provider client={trpcClient} queryClient={queryClient}>
<QueryClientProvider client={queryClient}>
{/* Your app here */}
</QueryClientProvider>
</trpc.Provider>
);
}
Wouldn't a useCallback() be a better fit?
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
domi?
domi?OP3y ago
I just got a little confused reading through it since it was useState, I thought it would be updated somehow. So is it wrapped into a useState to prevent re-renders of queryClient and trpcClient?
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
domi?
domi?OP3y ago
So would it work similarly if they wouldn't be wrapped into a useState?
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
domi?
domi?OP3y ago
hm oh that makes sense I think that would be better in terms of readability So you're sure that if I move queryClient and trpcClient to the outside of the component the app will function the same way? Or is there any performance benefit to having it in a useState
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
domi?
domi?OP3y ago
Thanks then So what do you think was the reason the docs recommended to do it this way?
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
domi?
domi?OP3y ago
Thanks
Want results from more Discord servers?
Add your server