Managing the Cache
A screen may need to reuse server-provided data, inspect what is already loaded, or discard entries after a workflow ends. Query provides explicit methods for each task. Its items cache holds result promises and expiration dates; its resolvers cache holds pending fetch promises and their abort controllers.
The examples use a stable query instance created with createQuery() as shown in Getting Started. Prefer these methods over editing the underlying stores so subscribers and request ownership stay consistent.
Inspect without fetching
Section titled “Inspect without fetching”For a diagnostic panel or an optional cached fallback, read a snapshot:
const profile = await query.snapshot<Profile>('/profile.json')const expiresAt = query.expiration('/profile.json')const storedKeys = query.keys()const pendingKeys = query.keys('resolvers')Here Profile is your application’s data type. snapshot<T>() returns Promise<T | undefined> and ignores expiration. Missing entries return undefined; a stored value can itself also be undefined, so use key enumeration or store inspection if you must distinguish the two. A custom cache’s rejected promise makes the snapshot reject.
expiration() returns Date | undefined. It returns the actual retained date, not a copy: do not mutate it. keys() defaults to 'items' and includes expired entries in the underlying store’s iteration order. It returns a new array, not a live key list.
An expiration date is not a removal timer. Query has no automatic garbage collector, maximum-size policy, or disk persistence. A long-lived application with unbounded unique keys must deliberately forget entries or provide a suitable synchronous custom store. See configuration for the store contract.
Seed a value before readers need it
Section titled “Seed a value before readers need it”If the application already has a profile from initial page data, seed it before mounting readers:
query.hydrate('/profile.json', { id: 1, name: 'Ada', role: 'Editor' }, { expiration: () => 30_000,})hydrate() returns void and writes synchronously. Readers now find the seeded value, and the hydrated event notifies existing subscribers. The optional expiration callback runs before the write and can throw. Without it, hydration has a zero-millisecond lifetime: the first ordinary read can return the seed and immediately start background revalidation.
Hydration is for establishing known data, especially server-to-browser handoff. Use mutation for ongoing application changes. Hydration is not queued behind mutations; it can interleave with an asynchronous mutation that later commits.
You can seed aliases with hydrate(['/api/profile', '/api/profiles/1'], profile), but the aliases retain the same object and promise. Query does not clone objects, merge entities, or keep aliases synchronized after later writes. Treat shared values as immutable.
Remove entries explicitly
Section titled “Remove entries explicitly”When data is no longer relevant, remove the exact representation or a deliberate set:
await query.forget('/profile.json')await query.forget(['/api/profiles/1', '/api/profiles/2'])await query.forget(/^\/api\/profiles\//)Each call removes matching stored entries and selected fresh render resources. await query.forget() with no arguments selects all of them in that instance. Removal does not have a built-in undo; reload from the source or seed a known value to recover.
forget() does not abort pending fetches. An active request can repopulate a key after it is forgotten. If your goal is to cancel and discard existing work, abort first:
query.abort('/profile.json', new Error('profile view closed'))await query.forget('/profile.json')Aborted callers still need rejection handling, and mounted consumers can start new work. For a logout or tenant change, stop rendering the old consumers and replace their instance; clearing a still-active shared instance is not an isolation boundary.
For an existing item, forget() deletes the entry before awaiting its promise and emitting forgotten with the old value. A rejected stored promise produces forgotten with undefined and does not prevent later entries from being removed. A pending custom stored promise can delay that event and subsequent keys. Forgetting a key with no item emits no forgotten event, even if it invalidates a fresh selection.
In React, a mounted hook normally keeps its displayed value after a forget event. clearOnForget opts into requesting a replacement; it is not a global cache-clearing guarantee.
Use low-level access for diagnostics
Section titled “Use low-level access for diagnostics”If you need to inspect storage machinery, caches() exposes live references:
const { items, resolvers } = query.caches()console.log(items.get('/profile.json')?.expiresAt)console.log(resolvers.get('/profile.json')?.controller.signal.aborted)The exported Cache<T> contract has synchronous get, set, delete, and keys. ItemsCacheItem<T> contains item: Promise<T> and expiresAt: Date; ResolversCacheItem<T> contains item: Promise<T> and controller: AbortController. Caches groups the two stores, and CacheType is 'items' | 'resolvers'.
Do not write through these references as an ordinary update strategy. Direct edits skip notifications, mutation serialization, fresh-resource alignment, and parts of request coordination. Use mutate, hydrate, forget, and abort for their respective tasks.