Using QueryClient defaultOptions.meta to inject Axios instance - Is this a good pattern? #10080
Replies: 2 comments 4 replies
-
|
Hm, I don’t think is that you create a closure over You can fix this by always reading the latest value in the queryFn from the injected client: this should be safe. The way The problem here is that |
Beta Was this translation helpful? Give feedback.
-
|
Thanks for the feedback @TkDodo! Just to make sure I understand correctly - moving the // ❌ Current pattern (potential stale closure)
const useListPets = () => {
const queryClient = useQueryClient();
const axiosInstance = getQueryAxiosInstance(queryClient); // Read once at render
return useQuery({
queryKey: ['pets'],
queryFn: () => axiosInstance.get('/pets'), // Closure over potentially stale value
});
};
// ✅ Recommended pattern (always fresh)
const useListPets = () => {
const queryClient = useQueryClient();
return useQuery({
queryKey: ['pets'],
queryFn: () => {
// Read on every queryFn execution = always latest value
const axiosInstance = getQueryAxiosInstance(queryClient);
return axiosInstance.get('/pets');
},
});
};And with this fix, is storing an axios instance in Thanks again for taking the time to review this! |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Context
I'm working on a feature for orval (OpenAPI code generator) to allow axios instance injection in generated React Query hooks. Before implementing it, I wanted to validate the approach with the community.
Feature request: orval-labs/orval#2887
The pattern I'm using
I store my configured axios instance in
QueryClient.defaultOptions.metaand retrieve it in my hooks:Why this pattern?
I originally implemented this pattern because I'm using Next.js with the Pages Router in SSR mode, and I needed two different axios instances:
With this approach, I can configure each QueryClient with its own axios instance depending on the context:
Now I want to take it further: I'm planning to publish my backend API as an SDK package on NPM. The idea is that consumers of my SDK can inject their own axios instance at runtime with their own configuration (auth interceptors, base URL, error handling, etc.). This pattern makes it possible without any tight coupling.
Questions
Is using
defaultOptions.queries.metaanddefaultOptions.mutations.metaa recommended way to share context like an HTTP client?Any performance concerns with calling
queryClient.getDefaultOptions()on every hook render?Is there a better alternative I should consider?
I've been using this pattern in production for a while and it works well. If the approach is validated, I'll implement it in orval so the community can benefit from it.
Thanks!
Beta Was this translation helpful? Give feedback.
All reactions