score:0

queryclientprovider is a react context provider. in react, you access the context via hooks because there is no guaranteed universal context. the hook returns you the most immediate context from the caller component's ancestors.

you cannot export it from app.js because it does not have a queryclientprovider above it. you could work around it. but that would not work either. you can only call the hook within a component and you cannot export something from inside the component. there is also the possibility of the whole site re-rendering with every request depending on your implementation.

overall, it seems like a bad idea.

score:0

there are basically three reasons why usequeryclient is preferred:

  1. it decouples your app from the actual implementation (the biggest win for me). this is especially relevant when doing testing. for example, when testing erroneous endpoints, react-query will do 3 retries with exponential backoff. that means your tests take longer and might even time-out for those cases. this can be solved by turning off retries for tests globally, via the queryclient. you can just provide a different queryclient to wrap your component in your test that has retries turned off.
  2. it is sometimes necessary to create the queryclient inside the app component (stable, on react state or an instance ref). for example, if you need to closure over values provided from another hook in your defaults passed to the queryclient, or, when doing server-side-rendering, where this is advised to avoid leaking data between requests and users.
  3. react-query internally uses usequeryclient to get the nearest queryclient from the provider. so you need to create the provider anyways.

score:1

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.


Related Query

More Query from same tag