In the quick start docs of react-query here there is the following example:
// Create a client
const queryClient = new QueryClient();
const App = function () {
return (
// Provide the client to your App
<QueryClientProvider client={ queryClient }>
<Todos />
</QueryClientProvider>
);
};
const Todos = function () {
// Access the client
const queryClient = useQueryClient();
// ...
return (
<>
...
</>
);
};
but I cannot understand why I should use the useQueryClient hook inside the Todos.
// Access the client
const queryClient = useQueryClient();
I mean couldn't I just export the the queryClient instance from my main file:
// App.js
export const queryClient = new QueryClient();
and then import it immediately inside Todos ?
// Todos.js
import { queryClient } from './App';
The reason I am asking this is because I want to use the queryClient instance apart from react (maybe inside a listener function from another library) and I was wondering that if I can only access it from a react hook (in order to not mess something up) then I won't be able to use it in some other way.
There are basically three reasons why useQueryClient is preferred:
useQueryClient to get the nearest QueryClient from the Provider. So you need to create the Provider anyways.yes, I think I got your doubt.
You can do this, is perfectly fine;
// App.js
export const queryClient = new QueryClient();
This is mostly how providers and context works, is just a bag to store global variables, and you will have access to the actual instance of that variable inside your ReactComponentTree.
That's why your <App/> must be wrapped with the provider to provide that context and use it from inside with useVariable()**
The thing is react-query provides functionalities that are tied to the react lyfecycle, and the preferable magic happens thanks to the useQuery() module and you won't be able to use that externally.
But, if you extract just the QueryClient to be called outside from React that could works. You just have to be aware of the implementation for the functionality that you will be using, mostly should works because tanner has known of separation of concerns, so probably the QueryClient provide specifics functions decoupled from React or any hook. Still be careful. And you can check the implementation on his repo, and ask more in deep to tanner directly, is a workaholic active on twitter xD, https://github.com/tannerlinsley.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With