T
TanStack7mo ago
deep-jade

Tanstack Query in separate packages

Hey crew, I've got a project where we have the main repo, and then we have a separate repo that we use for some "common" components to reuse, and we import that as a package into our main repo. Would I be able to use tanstack query hooks in the common components, and then have them work and tie into the query client properly when imported and used into the main repo? Thank you!
4 Replies
extended-salmon
extended-salmon7mo ago
I would generally try to keep the common components as dumb as possible. They should not even know of the existence of TSQ. The components should have props to pass the data (Query Results) and callback functions to handle events/updates (Mutations)
afraid-scarlet
afraid-scarlet7mo ago
I am looking for an answer to this as well. Having to force every app to write the same queries and mutations seems less ideal than being able to write them once in a reusable package.
stormy-gold
stormy-gold6mo ago
I'm confused as to what the problem is. I have a shared package with a hook that uses react-query inside of it and it seems to just work. I did externalize the deps of course
fascinating-indigo
fascinating-indigo6mo ago
Just to directly answer the OP's original question: Yes, if you use queries within your components (in your main application, or external), as long as they are using the hooks provided by Tanstack, that hook (no pun intended) into the react context, they will function as expected, since react context is passed through your main application into your components. --- To also agree with with ksgn, you generally should not do this for shared components, because a "shared component" should not be tied to any external dependency where possible. Obviously packages are a bit different, but relying on API requests in a shared component seems like bad practice, because you would expect an external component to be independent of any data fetching, and instead receive the necessary data as props. I don't know the architecture of your application though, and this may make sense in your use case. --- It is my general recommendation, as per the docs, that you would define each of your queries as query options using the queryOptions utility fromTanstack, and then export all your options for use elsewhere. In your case, if you have an external library for all of your components, this may also be a good place for you to co-locate all of your queryOptions for us in the main or other applications. For verdverm.com's point, yeah, if you exported all of your query options from one shared package, each of your applications would be able to import the query options and pass them to useQuery or any other query hook to make reusing them much easier.

Did you find this page helpful?