React Query - Client Provider in the _app.tsx using layouts

Viewed 560

I use layouts in my nextjs application, e.g. my homepage includes:

Homepage.getLayout = function getLayout(page: ReactElement) {
  return (
    <LayoutRoot auth={true}>
      <LayoutDefault>{page}</LayoutDefault>
    </LayoutRoot>
  );
};

Now, I'm trying to move queryClient into _app.tsx following this tutorial: https://react-query.tanstack.com/guides/ssr#using-hydration to prefetch some queries SSR.

Previously I have defined queryClient inside LayoutDefault, but in the RQ docs I've noticed:

Create a new QueryClient instance inside of your app, and on an instance ref (or in React state). This ensures that data is not shared between different users and requests, while still only creating the QueryClient once per component lifecycle.

After moving client instance into an app, the error shows:

Error: No QueryClient set, use QueryClientProvider to set one

My _app.tsx:

export default function MyApp({ Component, pageProps }: AppPropsWithLayout) {
  const [queryClient] = useState(() => new QueryClient());
  const getLayout = Component.getLayout ?? ((page) => page);
  const Layout = Component.layout ?? Fragment

  return getLayout(
      <QueryClientProvider client={queryClient} contextSharing={true}>
        <Hydrate state={pageProps.dehydratedState}>
          <div className="page-wrapper">
            <Component {...pageProps} />
          </div>
        </Hydrate>
      </QueryClientProvider>
 )

In the LayoutRoot and LayoutDefault I have a few contexts that use some queries/mutations.

How can I resolve this problem?

0 Answers
Related