When to use select vs other options for displaying subset of data?
Scenario: I want to toggle between displaying data1, data2, and combinedData.
I'm just getting started with react query and trying to understand what is the right approach:
1. useQuery to get the combinedData comprising of data1 and data2, use select to filter to data1 or data2 as needed
2. useQuery passing an argument to the queryFn to decide which dataset to fetch
3. have a useQuery for data1 and another useQuery for data2, conditionally render one or the other or the two combined
I'm thinking option 1 is the optimal thing to do, but are these all viable approaches?
6 Replies
eager-peach•12mo ago
1 or 3
rare-sapphireOP•12mo ago
With 2 I meant having the condition as a query key, is that fine?
eager-peach•12mo ago
I wouldn’t use 2 because you’re effectively having no cache in that scenario. Every time you go from data1, data2 or combinedData is an entire refetch
(ignoring any gcTime, simply the fact they’re different queryKey entries)
rare-sapphireOP•12mo ago
I thought each query key will produce a cache entry?
Borrowing an example from here - https://tkdodo.eu/blog/effective-react-query-keys
If I use
filters to choose data1 or data2, I thought there would be a separate cache for each?eager-peach•12mo ago
It's hard to say "use this" when every situation is unique. Every interface is different, every request RTT is different, etc. It's whatever fits you best.
What I meant by not liking option 2 is say you load
data1 in your interface and the key is ['data1']. Yes, you now have cached data for that entry.
Now you want to load ['data2']. Your app will make a new fetch and cache data2 into the queryCache under that key.
Now you want combinedData, you'd likely make a new fetch for data1 and data2 to make a cache entry for ['cominedData'] which is wasteful (you already have it client side).
You could getQueryData(['data1']) and getQueryData(['data2']) from the cache to return your combinedData instead of a new fetch, but that feels like unnecessary effort when option 1 or 3 are available.
Imagine you want combinedData immediately. You would need something like this to ensure you pull from cache or fetch:
rare-sapphireOP•12mo ago
Ah that makes sense. Thanks for the explanation!