What would be the right way to use RQ in a UI component library? #10100
-
|
Hi everyone! I just can't seem to find the right answer in the docs, maybe someone can help me out here. I'm building a UI component library which uses RQ to fetch data on its own (it's kind of a separate page meant to be shared across apps) and will be used in larger applications also using RQ. Here's the question: Should my lib initialize and isolate its own queryClient with its provider together or should it accept it from the host app and use theirs? The versions of RQ used by the app and my lib are very likely to be out of sync eventually (or practically always), I have little control over that. My current approach is isolating the libs RQ. What is your advice on this? Your help is much appreciated! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
|
Hey @dil-atelegdi ! For me, your current approach (isolating the lib's QueryClient) is the right call. But the issue with that is that TanStack Query uses React Context under the hood to distribute the QueryClient. So if your library and the host app ship different copies of @tanstack/react-query (even the same version, but duplicated in node_modules), they'll each create their own React context. That means that your library's useQuery calls won't find the host app's QueryClientProvider, and vice-versa. So if you can't control version alignment (which seems realistic to me for a shared UI library), creating your own QueryClient inside the library and wrapping your components with your own QueryClientProvider is the safest path. Your library's components will simply use the nearest provider (your isolated one), and the host app's queries stay on theirs. No collisions. (Like it was said by @TkDodo in some other discussion in my memories). The downside is obvious, you have no shared cache. If the host app already fetches /api/users and your library component also needs that data, it'll fetch again into its own separate cache. But for a "separate page" component like yours, this is probably fine. But it's worth being explicit about that and to be aware of that. |
Beta Was this translation helpful? Give feedback.
-
|
Hi @LeDevNovice, |
Beta Was this translation helpful? Give feedback.
Hey @dil-atelegdi !
For me, your current approach (isolating the lib's QueryClient) is the right call.
But the issue with that is that TanStack Query uses React Context under the hood to distribute the QueryClient. So if your library and the host app ship different copies of @tanstack/react-query (even the same version, but duplicated in node_modules), they'll each create their own React context. That means that your library's useQuery calls won't find the host app's QueryClientProvider, and vice-versa.
So if you can't control version alignment (which seems realistic to me for a shared UI library), creating your own QueryClient inside the library and wrapping your components with your own…