reactjsreact-querylernatanstackreact-query

How to share context between Lerna packages with React and @tanstack/react-query?


In my monorepo built with Lerna, I have two packages: app and components

General information

The app package is a clean install of a Remix Run app. The components package is a simple component library containing just a Button component I am using @tanstack/react-query to parse data, cache queries etc.

Public repo: https://github.com/kevinvugts/lerna-react-query-context/tree/main

Remix Lerna Package In the root.tsx of the app package, it's wrapped with the QueryClientProvider as stated in the docs.

When using hooks like useQuery, useQueryClient, or any other you prefer, it works without issues. However, this is only the case when invoked from within the Remix Lerna package.

Button

Regarding the Button, it's rendered in app -> routes -> _index.tsx. The crucial detail here is that the implementation of Button utilizes the useQueryClient hook from @tanstack/react-query. This is only feasible when it's called within the hierarchy of the QueryClientProvider, which I've done here.

The problem

When you uncomment line 18 from app -> routes -> _index.tsx the app throws the following error: Error: No QueryClient set, use QueryClientProvider to set one

This indicates to me that the QueryClientProvider's somehow lost its context while rendering the Button.

Addition of a separate context package

To determine if the issue is related to @tanstack/react-query, I created a separate context package. This package establishes a new context, a corresponding provider, and makes them available externally.

Subsequently, I wrapped the component in a manner similar to @tanstack/react-query, using the . From the Button component, I then invoked a function on the context to retrieve its value, checking if it matched the one from the Remix app. It did!

So what now?

To be entirely certain, I want to ensure that I haven't made any oversight that might invalidate my assumption about @tanstack/react-query being the culprit.

For clarity, I've verified that react, @tanstack/react-query, and related packages don't have duplicated instances. I've appropriately used peer/dev dependencies and ensured this in the rollup.config.js.

Regardless, any assistance would be greatly appreciated!"


Solution

  • I am closing this question in favor of the following solution:

    The problem I experienced was related to how React manages state across multiple versions of a specific package. Apparentely I was using a "^" symbol for @tanstack/react-query in one of my sub lerna packages which caused a version conflict. This stopped sharing state between the packages correctly.

    So for anyone who is experiencing this issue. Please check your versions thoroughly and also make sure you leverace the "resolutions" in the main package.json in the root of Lerna to make sure all of your packages beneath it use the same version.