Most performant way to filter a query list in React?

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?

@xeno9 without knowing the full extent of your requirements, I’m willing to bet a simple JavaScript .filter() on the list returned is going to be enough for your needs. Unless you have thousands of objects in the list, JavaScript is going to be fast enough you won’t notice any performance issues.

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)

As with anything performance, measure measure measure. Unless you’re working with very large amounts of data in a lot of different places, React/JavaScript is usually going to be fast enough for your needs. I find starting with a simple approach works great 99% of the time.

Hope that helps!

1 Like