Is it good practice to pass successful query data in Context ?
When using useQuery, you usually check if data is available (not fetching, no error). Once this check is made, does it make sense to pass the available data in a React <Context> so that all componenents within that tree do not have to check again if the data is fetching or not ?
3 Replies
harsh-harlequin•3y ago
I don't think so, no. TanStack Query uses a React Context provider to distribute the query client; you can read the data from the cache in any of the descendants of the query client provider. You'd need to check if the data is nullish even if you provided it yourself so I don't think it gains you much, if anything
I suppose you could return something else from the provider you roll yourself so the value is only ever exposed as data and not data or undefined, but it seems a little odd to me
Passing the data as props is often viable if you don't need to drill down through too many components, else I'd call the query hook or read the data from the cache imperatively, personally
generous-apricotOP•3y ago
But what if I need to drill down to a lot of components from a very deep tree ?
It actually seems odd to me that I would need to check for undefined 20 times in 20 different places
correct-apricot•3y ago
I would also just
useQuery wherever I need the data and embrace optional chaining. data?.something is not worse than data.something.
If you don't want that, you can pass data as props for sure, and putting it in context is just a way to avoid prop drilling. So yes, you can do that. Your sub-components will then only depend on "the context" rather than on "the query" itself, which can give you a bit more separation if that's what you are looking for. I've never gone that route though