Guidance around useQueries / combine() referential stability #6337
-
We love ReactQuery and I was really looking forward to the new After some testing it seams that the combine function will be run on each render. This means that I get a new combine-object, e.g., array on each render. Is there some way to prevent combine calls and serve the old combination result if none of the queries changed, i.e., all queries are settled with their data? The only workaround I came up with is to store the previous queries + combine result in a Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 5 replies
-
The result of combine is structurally shared, meaning if nothing changed, you'll get the same array reference back. Have you tried putting the result of combine as dependency to a useEffect for example ?
You'd need to check inside combine if all queries are settled and return something that you want if they aren't. That result will be structurally shared (see above), so it won't change reference even if it's called more than once. |
Beta Was this translation helpful? Give feedback.
-
Sorry to hijack this conversation but I have a similar question (tell me if I should open another thread :) ). In my case I need to combine the results into a new structure. More precisely: I want to reduce the results into a record of key/values. Something like that: type Device = {
id: string;
content: Content;
}
const combine = (
results: UseQueryResult<
Device,
Error
>[]
) => {
return results.reduce<Record<string, Device[]>>((acc, result) => {
const { data } = result;
if (!data) return acc;
return {
...acc,
[data.id]: data.content,
};
}, {});
}; In that case |
Beta Was this translation helpful? Give feedback.
-
Sorry for the late reply, I managed to debug my issue a bit more today and found the following:
Those two points were not clear to me and might make a good addition to the docs. |
Beta Was this translation helpful? Give feedback.
Sorry for the late reply, I managed to debug my issue a bit more today and found the following:
UseQueryResult<TResult, Error>[]
will always change its reference.combine
it was essential that I don't return anynew MyClass()
object. Neither aMap
,Set
or custom class.Those two points were not clear to me and might make a good addition to the docs.