113

I was trying React Query and got this at the start of my React app.

screenshot of the error: "Error: No QueryClient set, use QueryClientProvider to set one"

import React from 'react'
import { useQuery } from "react-query";
    
const fetchPanets = async () => {
    const result = await fetch('https://swapi.dev/api/people')
    return result.json()
    }
    
const Planets = () => {
    const { data, status } = useQuery('Planets', fetchPanets)
    console.log("data", data, "status", status)
    return (
        <div>
            <h2>Planets</h2>
        </div>
    )
}
    
export default Planets
2
  • 2
    in 2022, this problem resurface once again but I dont know what is the correct version to make the problem go away :( Commented Sep 30, 2022 at 7:18
  • 1
    Make sure you're installing with npm i @tanstack/react-query for v4+. Commented Feb 26, 2023 at 9:51

22 Answers 22

111

As the error suggests, you need to wrap your application in a QueryClientProvider. This is on the first page of the docs:

import { QueryClient, QueryClientProvider, useQuery } from 'react-query'

const queryClient = new QueryClient()

export default function App() {
   return (
     <QueryClientProvider client={queryClient}>
       <Example />
     </QueryClientProvider>
   )
}
Sign up to request clarification or add additional context in comments.

1 Comment

I use package "react-query" first then I realize there is a newer version "@tanstack/react-query". So after a while a realize I use the provider from the newer version but consumer code was using "useMutation" from the old package. That's why it cannot not find the Provider for my old code.
50

Make sure your imports are consistent throughout your project!

If @TKDodo answer did not solve your problem, it can also be due to a package name change on its different major versions. After Version 3, the name of the package changed based on its migration guide:

react-query <= v3 : react-query

react-query >= v4 : @tanstack/react-query

In my case I was importtng from 'react-query' in one place and '@tanstack/react-query' in another.

4 Comments

Yep I did the same thing
Same problem here. Change all of them and it works fine
I did the same thing too; I changed it to: import { useMutation } from "@tanstack/react-query"; And then, everything worked well.
Same for me, changed from react-query to @tanstack/react-query resolves for me
44

While this is most commonly caused by not having your application wrapped in a <QueryClientProvider>, in my case it happened because I was importing some shared components, which ended up with a different context. You can fix this by setting the contextSharing option to true

That would look like:

 import { QueryClient, QueryClientProvider } from 'react-query'
 
 const queryClient = new QueryClient()
 
 function App() {
   return <QueryClientProvider client={queryClient} contextSharing={true}>...</QueryClientProvider>
 }

From the docs: (https://react-query.tanstack.com/reference/QueryClientProvider)

contextSharing: boolean (defaults to false)

Set this to true to enable context sharing, which will share the first and at least one instance of the context across the window to ensure that if React Query is used across different bundles or microfrontends they will all use the same instance of context, regardless of module scoping.

3 Comments

doesn't always work idk why
The contextSharing option has been deprecated and will be removed in the next major version
@azu did you find a solution that works with v4? I am facing the same issue and context sharing doesn't seem like a solution.
16

Just make changes like below it will work fine

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { QueryClient, QueryClientProvider } from "react-query";
const queryClient = new QueryClient();

ReactDOM.render(
  <QueryClientProvider client={queryClient}>
    <App />
  </QueryClientProvider>,
  document.getElementById('root')
);

Comments

8

I got that error when trying to add the react-query devtools.

The problem was I was installing it wrongly according my version, I was using react-query v3.

WRONG FOR react-query V3 (GOOD FOR V4)

import { ReactQueryDevtools } from '@tanstack/react-query-devtools';

OK FOR react-query V3

import { ReactQueryDevtools } from 'react-query/devtools';

1 Comment

This was me. I don't know how you found this but fair play.
5
import {  QueryClient, QueryClientProvider, useQuery } from 'react-query';
const queryClient = new QueryClient();
const fetchPanets = async () => {
    const result = await fetch('https://swapi.dev/api/people')
    return result.json()
}

const Planets = () => {
    const { data, status } = useQuery('Planets', fetchPanets)
    console.log("data", data, "status", status)
    return (
        <div>
            <h2>Planets</h2>
        </div>
    );
}


export default function Wraped(){
return(<QueryClientProvider client={queryClient}>
        <Planets/>
    </QueryClientProvider>
);
    
}

1 Comment

Thanks for this one mate. the Wrapped type was the missing piece for me.
4

Single SPA (micro-frontend) - React Query v3.34.15

I was getting this error while trying to integrate a sigle-spa react parcel into the root application.

I used craco-plugin-single-spa-application for the building of a CRA app as a way to adapt it for a parcel. In the entry config I was pointing to my single-spa-react config.

// craco.config.js

const singleSpaApplicationPlugin = require('craco-plugin-single-spa-application')

module.exports = {
  plugins: [
    {
      plugin: singleSpaApplicationPlugin,
      options: {
        orgName: 'uh-platform',
        projectName: 'hosting',
        entry: 'src/config/single-spa-index.cf.js',
        orgPackagesAsExternal: false,
        reactPackagesAsExternal: true,
        externals: [],
        minimize: false 
      }
    }
  ]
}

In the single-spa-index.cf.js file I had the following configs.

import React from 'react'
import ReactDOM from 'react-dom'

import singleSpaReact from 'single-spa-react'

import App from '../App'

const lifecycles = singleSpaReact({
  React,
  ReactDOM,
  rootComponent: App,
  errorBoundary() {
    return <div>Ocorreu um erro desconhecido!</div>
  }
})

export const { bootstrap, mount, unmount } = lifecycles

After reading a bunch of forums and the react-query documentation, the only thing that I figured out I needed to change was pass in the QueryClientProvider the prop contextSharing as true. After had did this change, ran the building and access the route that opens my parcel. I got the same error.

import React from 'react'
import ReactDOM from 'react-dom'
import { QueryClient, QueryClientProvider } from 'react-query'
import { ReactQueryDevtools } from 'react-query/devtools'

import App from './App'

const queryClient = new QueryClient()

const isDevelopmentEnv = process.env.NODE_ENV === 'development'

if (isDevelopmentEnv) {
  import('./config/msw/worker').then(({ worker }) => worker.start())
}

ReactDOM.render(
  <React.StrictMode>
    <QueryClientProvider contextSharing={true} client={queryClient}>
      <App />
      {isDevelopmentEnv && <ReactQueryDevtools initialIsOpen={false} />}
    </QueryClientProvider>
  </React.StrictMode>,
  document.getElementById('root')
)

But, how do I solved that. Well, it was was simple. I couldn't even imagine why it was working locally. But not after building and integration.

The problem was because I put the React Query Provider inside the index o the application and in my single-spa-index.cf.js I was importing import App from '../App' which really wasn't wrapped by the provider. Once I also was importing App in the application index, where It was wrapped making It works locally. 😢😢

So after figure that out, my code was like that: CODE AFTER SOLUTION

// craco.config.js
const singleSpaApplicationPlugin = require('craco-plugin-single-spa-application')

module.exports = {
  plugins: [
    {
      plugin: singleSpaApplicationPlugin,
      options: {
        orgName: 'uh-platform',
        projectName: 'hosting',
        entry: 'src/config/single-spa-index.cf.js', 
        orgPackagesAsExternal: false,
        reactPackagesAsExternal: true,
        externals: [], 
        minimize: false 
      }
    }
  ]
}

// src/config/single-spa-index.cf.js 
import React from 'react'
import ReactDOM from 'react-dom'

import singleSpaReact from 'single-spa-react'

import App from '../App'

const lifecycles = singleSpaReact({
  React,
  ReactDOM,
  rootComponent: App,
  errorBoundary() {
    return <div>Ocorreu um erro desconhecido!</div>
  }
})

export const { bootstrap, mount, unmount } = lifecycles


// App.tsx
import { QueryClient, QueryClientProvider } from 'react-query'
import { ReactQueryDevtools } from 'react-query/devtools'

import { config } from 'config/react-query'
import Routes from 'routes'
import GlobalStyles from 'styles/global'

import * as S from './styles/shared'

const queryClient = new QueryClient(config)

const isDevelopmentEnv = process.env.NODE_ENV === 'development'

if (isDevelopmentEnv) {
  import('./config/msw/worker').then(({ worker }) => worker.start())
}

function App() {
  return (
    <QueryClientProvider contextSharing={true} client={queryClient}>
      <S.PanelWrapper>
        <Routes />
        <GlobalStyles />
      </S.PanelWrapper>

      <ReactQueryDevtools initialIsOpen={false} />
    </QueryClientProvider>
  )
}

export default App

// index.tsx
import { StrictMode } from 'react'
import ReactDOM from 'react-dom'

import App from './App'

ReactDOM.render(
  <StrictMode>
    <App />
  </StrictMode>,
  document.getElementById('root')
)

Well, it was long but I hope it helps someone that's undergoing for the same problem as mine. 🙌🙌🙌

Comments

3

In my case I accidentally used two different versions of react-query in my modules.

Comments

3

Just be careful when upgrade from react-query v3 to @tanstack/react-query v4.

Ensure that you replace all imports as "react-query" to "@tanstack/react-query" and then run yarn remove the lib that you won't use anymore, otherwise you may accidentally import the unexpected one. This happened to me and caused this error.

Comments

2

I was trying to fix the same thing:

I followed the React Query docs and used the concept of Higher Order Component

See if it helps:
import React from 'react';
import { QueryClient, QueryClientProvider, useQuery } from 'react-query';

import Planet from './Planet';

const queryClient = new QueryClient();

const fetchPlanets = async () => {
    const res = await fetch('http://swapi.dev/api/planets/');
    return res.json();
}

const Planets = () => {

    const { data, status } = useQuery('planets', fetchPlanets);

    return (
        <div>
            <h2>Planets</h2>
            { status === 'loading' && (<div>Loading data...</div>)}
            { status === 'error' && (<div>Error fetching data</div>)}
            {
                status === 'success' && (
                    data.results.map(planet =>
                        <Planet
                            key={planet.name}
                            planet={planet}
                        />
                    )
                )
            }
        </div>
    )
}

// Higher order function
const hof = (WrappedComponent) => {
    // Its job is to return a react component warpping the baby component
    return (props) => (
        <QueryClientProvider client={queryClient}>
            <WrappedComponent {...props} />
        </QueryClientProvider>
    );
};

export default hof(Planets);

1 Comment

Awesome work! This is a great pattern to follow for useQuery
2

This usually happens when you have more than one versions of @tanstack/react-query or react-query. Ideally you should have only one of them.

Try checking your lock file and package.json. Before deleting any dependency please check these two things to avoid potential pitfalls :-

  1. Check the dependency is not being used anywhere in your codebase.
  2. Try doing yarn why dependencyName to see why the dependency was installed in the first place if it's a peer dependency of any other package try upgrading/downgrading that package if not you can just remove it from your package.json delete node_modules your build folder and reinstall all your dependencies.

In my case I had @tanstack/react-query and react-query both present Deleting react-query solved the problem.

Comments

1

For me it's caused by react-query devtools

  • "react-query": "^3.39.3"
  • "react-query-devtools": "^2.6.3"

and importing like this:

  • import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
  • import { ReactQueryDevtools } from 'react-query/devtools';

So, the solution is change the version using:

  • "@tanstack/react-query": "^4.13.0",
  • "@tanstack/react-query-devtools": "^4.13.0",

and import like this:

  • import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
  • import { ReactQueryDevtools } from '@tanstack/react-query-devtools';

Comments

1

If you want to avoid bloating your App.tsx you can use the same solution provided by others by with a different approach to keep your code tidy.

Create a src/contexts/ReactQueryProvider.tsx file:

import React from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'

const queryClient = new QueryClient()

interface Props {
  children: React.ReactNode
}

const ReactQueryProvider: React.FC<Props> = ({ children }) => {
  return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
}

export default ReactQueryProvider

And then in your App.tsx you can wrap your existing app into it.

import React from 'react'

import AppRouter from './routers/AppRouter'
import Header from './components/Header'
import ReactQueryProvider from './contexts/ReactQueryProvider'


const App: React.FC = () => {
  return (
      <div className="App">
        <ReactQueryProvider> // <= use it as a wrapper
          <Header/>
          <AppRouter/>
        </ReactQueryProvider>
      </div>
  )
}

export default App

I use this techniques with all my providers, so each of them has their configuration in their file, and the main App file remains tidy.

Comments

0

In my case

Error import { QueryClient, QueryClientProvider } from "@tanstack/react-query";

Solution import { QueryClient, QueryClientProvider } from "react-query";

remove it @tanstack/

Comments

0

I have faced a similiar issue and I fixed by upgrading the package

npm i @tanstack/react-query@beta

Comments

0

in my case I was trying to access the user from react query cache in my <App /> component before registering the <QueryClientProvider>.

function App() {
  const { user } = useCurrentUser();

  console.log({ user });

  return (
    <QueryClientProvider client={queryClient}>
      <Navbar />
      <Routes />
      <Loading />
      <Toaster />
      <ReactQueryDevtools />
    </QueryClientProvider>
  );
}

export default App;

Comments

0

You can not use useQuery inside the same functional component where you are using QueryClientProvider. thanks

1 Comment

Welcome to Stack Overflow! Thank you for your answer. Please provide more details about your solution. Code snippets, high quality descriptions, or any relevant information would be great. Clear and concise answers are more helpful and easier to understand for everyone. Edit your answer with specifics to raise the quality of your answer. For more information: How To: Write good answers. Happy coding!
0

I'm using '@tanstack/react-query'so all solution didn't help me :( Only solution that I found was on their library: https://tanstack.com/query/v4/docs/framework/react/reference/QueryClientProvider

import { QueryClient, QueryClientProvider } from '@tanstack/react-query';    
const queryClient = new QueryClient();
describe('Example page', () => {
    <QueryClientProvider client={queryClient}>
        <Example />
    </QueryClientProvider>
});

Comments

0

i had the same error and fixed it changing @tanstack/react-query version ^5
to version "^4.33.0" on the package.json

the issue was point out here https://github.com/thirdweb-dev/dashboard/issues/2084

Comments

0

in my case, i was importing the function using require instead of import

from:

const { useQuery } = require("@tanstack/react-query");

to:

import { useQuery } from "@tanstack/react-query";

Comments

0

In my case, I was using a custom ModalContextProvider, which was responsible for rendering modal components, and it was placed above the QueryClientProvider. This caused an error. To fix it, I simply moved the ModalContextProvider inside the QueryClientProvider.

Before:

<ModalContextProvider>
    <QueryClientProvider client={queryClient}>
      {children}
      <ReactQueryDevtools initialIsOpen={false} />
    </QueryClientProvider>
  </ModalContextProvider>

After:

<QueryClientProvider client={queryClient}>
    <ModalContextProvider>
      {children}
      <ReactQueryDevtools initialIsOpen={false} />
    </ModalContextProvider>
  </QueryClientProvider>

Comments

0

I had this exact issue and solved it by converting my npm package from CommonJS to ESM.

Root Cause

My package was built as **CommonJS** while Vite is **ESM-first**. Vite wraps CommonJS packages during pre-bundling, creating separate module instances. Since React Context uses ===` reference equality, different instances = no context found.

Solution

1. package.json:
    {
      "type": "module",
      "exports": {
        ".": {
          "types": "./dist/index.d.ts",
          "import": "./dist/index.js"
        }
      }
    }
  1. tsconfig.json:
    {
      "compilerOptions": {
        "module": "ESNext",
        "moduleResolution": "bundler"
      }
    }

Note: Node.js consumers will need "type": "module" or .mjs extensions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.