Open History to see the last commit
1---
2id: useQueries
3title: useQueries
4---
5β
6The `useQueries` hook can be used to fetch a variable number of queries:
7β
8```tsx
9const ids = [1, 2, 3]
10const results = useQueries({
11 queries: ids.map((id) => ({
12 queryKey: ['post', id],
13 queryFn: () => fetchPost(id),
14 staleTime: Infinity,
15 })),
16})
17```
18β
19**Options**
20β
21The `useQueries` hook accepts an options object with a **queries** key whose value is an array with query option objects identical to the [`useQuery` hook](../useQuery.md) (excluding the `queryClient` option - because the `QueryClient` can be passed in on the top level).
22β
23- `queryClient?: QueryClient`
24 - Use this to provide a custom QueryClient. Otherwise, the one from the nearest context will be used.
25- `combine?: (result: UseQueriesResults) => TCombinedResult`
26 - Use this to combine the results of the queries into a single value.
27β
28> 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.
29β
30**placeholderData**
31β
32The `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.
33β
34**Returns**
35β
36The `useQueries` hook returns an array with all the query results. The order returned is the same as the input order.
37β
38## Combine
39β
40If 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.
41β
42```tsx
43const ids = [1, 2, 3]
44const combinedQueries = useQueries({
45 queries: ids.map((id) => ({
46 queryKey: ['post', id],
47 queryFn: () => fetchPost(id),
48 })),
49 combine: (results) => {
50 return {
51 data: results.map((result) => result.data),
52 pending: results.some((result) => result.isPending),
53 }
54 },
55})
56```
57β
58In 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.
59β
60### Memoization
61β
62The `combine` function will only re-run if:
63β
64- the `combine` function itself changed referentially
65- any of the query results changed
66β
67This 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 to a stable function reference if it doesn't have any dependencies.