I have a query that returns a list of items.
I want my user to be able to filter those items by selecting an item type (via radio buttons) and then only displaying items that match the selected type.
What is the most performant way to achieve this using Apollo client?
E.g. should I use a filter on the
useQuery hook? Should I update the cache?
If this is a large list and you would like to avoid recomputing the filtered list on every render, consider memoizing the result by combining it with React’s
useMemo. Thankfully Apollo client will return an object from
useQuery that is referentially stable, so you can ensure the filtered array will only be recomputed when data has changed.
Should I update the cache?
This is also an option, though I think you’ll find a few issues with this approach:
- Depending on your
fetchPolicy, queries will read from the cache to get data. If your cache only contains filtered data, you won’t have the full data set to work against when those radio buttons change the selected type.
- Its awkward to implement. You’d likely need a
useEffect to sync filtered changes back to the cache, but there is a potential you end up in an infinite loop if you’re not careful (new data causes
useEffect to fire, which writes to the cache, which causes a rerender; rinse and repeat)
Hope that helps!