useQueries

· abundance's blog


The useQueries hook can be used to fetch a variable number of queries:

1const ids = [1, 2, 3]
2const results = useQueries({
3  queries: ids.map((id) => ({
4    queryKey: ['post', id],
5    queryFn: () => fetchPost(id),
6    staleTime: Infinity,
7  })),
8})

Options

The useQueries hook accepts an options object with a queries key whose value is an array with query option objects identical to the useQuery hook (excluding the queryClient option - because the QueryClient can be passed in on the top level).

Having the same query key more than once in the array of query objects may cause some data to be shared between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired structure.

placeholderData

The placeholderData option exists for useQueries as well, but it doesn't get information passed from previously rendered Queries like useQuery does, because the input to useQueries can be a different number of Queries on each render.

Returns

The useQueries hook returns an array with all the query results. The order returned is the same as the input order.

Combine #

If you want to combine data (or other Query information) from the results into a single value, you can use the combine option. The result will be structurally shared to be as referentially stable as possible.

 1const ids = [1, 2, 3]
 2const combinedQueries = useQueries({
 3  queries: ids.map((id) => ({
 4    queryKey: ['post', id],
 5    queryFn: () => fetchPost(id),
 6  })),
 7  combine: (results) => {
 8    return {
 9      data: results.map((result) => result.data),
10      pending: results.some((result) => result.isPending),
11    }
12  },
13})

In the above example, combinedQueries will be an object with a data and a pending property. Note that all other properties of the Query results will be lost.

Memoization #

The combine function will only re-run if:

This means that an inlined combine function, as shown above, will run on every render. To avoid this, you can wrap the combine function in useCallback, or extract it so a stable function reference if it doesn't have any dependencies.