-
I’ve recently been wondering if it could make sense to use the queryClient without any hooks at all, and instead configure the router to revalidate whenever there's any new data in the query-cache: function useRevalidateOnQueryClientChange() {
const revalidator = useRevalidator()
const queryClient = useQueryClient()
useEffect(() => {
const unsubscribe = queryCache.subscribe((event) => {
if (
event.type === "updated" &&
(event.action.type === "error" ||
event.action.type === "success" ||
event.action.type === "setState")
)
revalidator.revalidate() // maybe do some debouncing here...
return () => unsubscribe()
}, [revalidator, queryClient])
}
function clientLoader() {
return queryClient.ensureQueryData({
...query(),
revalidateIfStale: true
})
}
function Route() {
const data = useLoaderData()
useRevalidateOnQueryClientChange()
...
} The motivation for this is to simplify working with complex dependent queries. Our API unfortunately requires composing results from many endpoints. Combining this data quickly gets messy, since you have to track and combine loading/error states for each query (nevermind suspense). By comparison, Promises are more composable than hooks and generally better understood by developers. I don’t think this would lead to too many revalidations because:
Stale while revalidate would still work, because Has anyone attempted the above pattern? Do you think this approach is reasonable? I'm asking this mostly because #9135 intends to deprecate |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
If it works for you, sure, why not. Just keep in mind that queries that don’t have an observer with That’s because React Query doesn’t know that you are “using” a query unless you explicitly subscribe to it with |
Beta Was this translation helpful? Give feedback.
If it works for you, sure, why not. Just keep in mind that queries that don’t have an observer with
useQuery
or a similar hook are consideredinactive
(you can see that in the devtools), which means they are eligible for garbage collection, they won’t be refetched withinvalidateQueries
automatically etc.That’s because React Query doesn’t know that you are “using” a query unless you explicitly subscribe to it with
useQuery
. Subscribing to the whole cache and doing your own thing bypasses this a bit.