T
TanStack3y ago
correct-apricot

new QueryClient instantiated in a function component

Hi, so I want to trigger toasts on errors, and the toasts can only be controlled through hooks. In this case, instead of instantiating the query client globally, I made a wrapper rq provider which has access to the toast provider:
export const RQClientProvider = ({
children,
}: {
children: React.ReactNode;
}) => {
const toast = useToastController();
const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: 1,
refetchOnWindowFocus: false,
staleTime: 10_000,
},
},
queryCache: new QueryCache({
onError: (error_: any) => {
const error = error_ as AxiosError;
toast.show("Error", {
customData: {
preset: "error",
},
message:
error.response?.status === 404 ? "Not found" : error.message,
});
},
}),
});

return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;
export const RQClientProvider = ({
children,
}: {
children: React.ReactNode;
}) => {
const toast = useToastController();
const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: 1,
refetchOnWindowFocus: false,
staleTime: 10_000,
},
},
queryCache: new QueryCache({
onError: (error_: any) => {
const error = error_ as AxiosError;
toast.show("Error", {
customData: {
preset: "error",
},
message:
error.response?.status === 404 ? "Not found" : error.message,
});
},
}),
});

return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;
So my question is: is it still okay to instantiate a client in this way? There's only 1 way to trigger this provider rerender - which is by changing the theme (as my theme provider and toast provider are coming from the same library)
4 Replies
correct-apricot
correct-apricotOP3y ago
I considered wrapping it in a useCallback useMemo but is it really necessary when there's really no way to rerender it too many times
like-gold
like-gold3y ago
useState for one-time initializations
Why you shouldn't rely on useMemo for guaranteed referential stability but prefer useState instead
like-gold
like-gold3y ago
if you change a theme, you'd delete all your queries with that. probably not what you want : https://tkdodo.eu/blog/react-query-fa-qs#2-the-queryclient-is-not-stable
React Query FAQs
Answering the most frequently asked React Query questions
correct-apricot
correct-apricotOP3y ago
damn, you're correct. thanks!

Did you find this page helpful?