Next.js Discord

Discord Forum

Cannot import from react-query in server components

Asian black bear posted this in #help-forum
Open in Discord
Asian black bearOP
Hi, I'm new to NextJS, and I'm trying to follow this guide (written for NextJS 13) to set up react-query:

However, importing anything from 'react-query' triggers an error in server components:
createContext only works in Client Components. Add the "use client" directive at the top of the file to use it.

This is because of a top-level call to createContext in QueryClientProvider:
export const QueryClientContext = React.createContext<QueryClient | undefined>(

I can workaround this for some exports by importing directly from react-query/core. But the Hydrate component, which is needed on the server, is in react-query/react.

The repro is pretty simple:
1. Create a new NextJS app router project.
2. Install react-query : npm install react-query
3. Run the dev server with npm run dev and open it in your browser. Observe that it works as expected.
4. In Page.tsx, import and use any export from react-query:
import { QueryClient } from 'react-query';
export default function Home() {
  const client = new QueryClient(); // In practice you shouldn't create the client here, I just wanted a simple example for the repro.

Observe the createContext error described above.

5. Change the import to import { QueryClient } from 'react-query/core';

Observe that there is no longer an error, and the app functions as expected

6. Undo your changes to Page.tsx, then import and use something from react-query/react:
import { Hydrate } from 'react-query/react'; // or just from react-query
return (
  <Hydrate state={{}}>...</Hydrate>

Observe that the createContext error occurs.

node 21.2.0
next 14.0.3
react-query 3.39.3

5 Replies

Asian black bearOP
Ah, I believe this is my fault for using react-query rather than @tanstack/react-query. Looks like react-query is an older version. Will update once I confirm the fix.
the major version (v3) for react-query does not contain "use client" directives
Asian black bearOP
Yep, problem solved by switching to v5 from @tanstack/react-query and following this guide:
Round sardinella
I'm tired of these type of enigmatic errors...
neither where it comes from is clear, nor the solution. it's as if reactjs is an obscure library