Should gcTime refer to the cached entries, or the cache itself
For some reason I was under the impression that gcTime referred to the time an entire query cache attached to a useQuery hook would be considered stale. But it seems like it's applied to each individual cache entry.
So doing
useQuery({ queryKey: ["foo", x], gcTime: 0
will wipe each previously viewed cache entry whenever x changes.
The behavior I'd like to achieve is for a given useQuery hook to keep all cached entries around for some time, until that hook itself unmounts, at which point I'd clear the cache for that query entirely.
The best way I can think of would be for the hook's parent component to just render a QueryClientProvider with its own queryClient. When when it unmounts, and re-mounts, a fresh queryClient (with a fresh cache) should take over.
Would that work properly? (ignoring the fact that I can no longer share cache entries from other queries, elsewhere in the app)
Is there a better way?
6 Replies
mute-gold•12mo ago
will wipe each previously viewed cache entry whenever x changes.yes, that's what it does.
gcTime
starts to run when there's no more active observer, and when you change x
from 0
to 1
and have no other observer for ['foo', 0]
, that entry can be gargabe collected
at which point I'd clear the cache for that query entirely.
['foo', 0]
and ['foo', 1]
are two different queries. A query is a cache entry - they know nothing about each other 🙂
can you elaborate what you are trying to achieve with that?flat-fuchsiaOP•12mo ago
I browse to a /todos page. There's a
useQuery({ queryKey: ["todos", searchfilters]
query on it. It caches in whatever way.
I browse away to another page. At the point in which I browse away, I want the entire cache for "todos" to disappear completely.
Having typed that all out, maybe I should just do this in the root todos component?
useEffect(() => {
return () => queryClient.invalidateQuery(["todos"])
}, []);
mute-gold•12mo ago
not invalidateQueries, but removeQueries, yes.
flat-fuchsiaOP•12mo ago
til removeQueries - yeah, that seems to be what I want (seems invalidateQueries would work, too, it'd just leave the (now unused) entries in the cache, but marked as stale?
I'm just curious - what happens if you screw up and call removeQueries on queries which are currently active - will it error out? Immediately refetch?
mute-gold•12mo ago
with invalidate, yes, it's marked as stale. But you'll still get that stale data on the next mount
if you removeQueries, nothing happens. the cache entry is removed, observers aren't notified. On the next render of your component, you'll get a hard loading state
if you want an immediate refetch, you want
resetQueries
flat-fuchsiaOP•12mo ago
beautiful - thank you so much!