I built most of an admin console for a clinical dictation product, in React with RTK Query. Practice admins use it to manage people and devices and to open dictations, which carry a patient's name, transcript and note. Moving between screens showed loading skeletons every time, and the next job was to make it feel faster without leaving patient data anywhere it should not be.
The short answer I landed on: cache API data in memory only, never in browser storage and never in the browser's HTTP cache. Show cached lists at once and refetch them in the background when they are older than 30 seconds. Keep lists for 5 to 10 minutes after their screen closes. Never automatically re-read a record whose every read is audited. Empty the whole cache the moment the signed-in admin changes.
Where API responses are allowed to live
A response can end up in the browser's HTTP cache, in localStorage or IndexedDB if the app puts it there, or in JavaScript memory. Only the last disappears when the tab closes. For patient data I wanted one cache, the one RTK Query keeps in the Redux store, and nothing on disk.
RTK Query's fetchBaseQuery passes extra options through to fetch, so one option on the base query covers every endpoint:
const rawBaseQuery = fetchBaseQuery({ baseUrl: env.apiBaseUrl, cache: 'no-store' })
export const REVALIDATE_AFTER_S = 30
export const baseApi = createApi({
reducerPath: 'api',
baseQuery,
tagTypes: ['User', 'Invite', 'Device', 'Dictation', 'Provider'],
refetchOnFocus: true,
refetchOnReconnect: true,
refetchOnMountOrArgChange: REVALIDATE_AFTER_S,
endpoints: () => ({}),
})
cache: 'no-store' tells the browser not to read or write its HTTP cache for the request. I set it on the client so the rule does not depend on every response carrying the right header. The list responses hold patient names, and one base-query option covers them all.
The store has no persistence layer, and the project notes now say so as a rule: no localStorage or IndexedDB for API data.
Stale-while-revalidate and keepUnusedDataFor in RTK Query
Stale-while-revalidate means showing the cached copy immediately and fetching a fresh one in the background, so the screen is never blank and is only briefly out of date. In RTK Query this is one setting. refetchOnMountOrArgChange accepts a number of seconds: when a component mounts on a cached query, it gets the cached data straight away, and a refetch runs only if that data is older than the number.
I set it to 30 seconds for the whole API. The focus and reconnect refetches were already on. A cached list opened within 30 seconds makes no request. After that it renders from cache and updates when the response arrives.
Revalidation only helps if there is something cached to show. RTK Query drops a query's data once no component is subscribed to it, after keepUnusedDataFor seconds, and the library default is 60.
I raised it per endpoint rather than globally. Users, invites and devices keep their data for 600 seconds, matching the providers list, which was already at 600. The dictation list, whose rows contain patient names, gets 300:
getDictations: build.query({
query: (filters = {}) => ({ url: listUrl, params: listParams(filters) }),
providesTags: (result) => [
{ type: 'Dictation', id: 'LIST' },
...(result?.dictations.map(({ id }) => ({ type: 'Dictation', id })) ?? []),
],
// Pages and tabs already seen come back at once (and revalidate in the background). Patient
// names are in these rows: memory only, emptied when the admin signs out.
keepUnusedDataFor: 300,
}),
(listUrl stands in for the real path.) The existing listParams helper leaves out empty filters, so equal filters share one cache entry, and each page and tab the admin has visited is its own entry that comes back instantly.
Never refetch an audited read automatically
The dictation detail is the exception to all of the above. It returns the patient, the transcript and the note, and the server writes each fetch to an audit log as that admin viewing the record. A background refetch here is not free: it would add an audit entry for a view the admin never asked for.
The first version already handled part of this. The detail endpoint had keepUnusedDataFor: 15, and its hook turned off refetching on focus and reconnect. My new app-wide 30-second revalidation would have quietly broken that, because it applies on mount to every query. So the hook now opts out of that as well:
const { data, error, isLoading, isError, refetch } = useGetDictationQuery(dictationId, {
// Each read is audited as a view: never again on mount (the app-wide revalidation), focus or
// reconnect.
refetchOnMountOrArgChange: false,
refetchOnFocus: false,
refetchOnReconnect: false,
})
Two other pieces of the app follow the same rule. Archiving patches the open record with updateQueryData instead of invalidating it, because a refetch would be another audited read. And the signed audio URL is requested through a mutation dispatched with track: false, so it goes to the player and is never held in the store.
The lesson for me was that a global cache default is a decision about every endpoint, including the ones where a repeat request has a side effect.
Clearing the cache when the signed-in user changes
An in-memory cache still outlives a sign-out if the tab stays open. On a shared computer, nothing from one session should be shown to the next, even for a moment before the first response arrives. I added a listener on the session action that compares the admin id before and after:
const sessionListener = createListenerMiddleware()
sessionListener.startListening({
actionCreator: sessionChanged,
effect: (action, api) => {
const previousId = api.getOriginalState().auth.user?.id ?? null
const nextId = action.payload?.id ?? null
if (previousId === nextId) return
api.dispatch(baseApi.util.resetApiState())
clearToasts()
},
})
resetApiState empties every cached query. Comparing ids rather than reacting to every session action means a profile refresh for the same admin keeps the cache. Toasts are cleared in the same place, because one of them can carry an Undo button, and an Undo must not run under the next admin's session.
Data also leaks through addresses. The dictation search puts its text, a patient's name or record number, in a q query parameter on both the page and the list request. Addresses sent to error monitoring are scrubbed first: the email, code and q values are removed, so a search never leaves the browser inside an error report.
Cache-Control for the app shell and hashed assets
The app's own files are the opposite case: not sensitive, and safe to cache hard. The build output has content-hashed file names under /assets/, so the hosting config marks them immutable for a year and makes everything else revalidate:
{
"routes": [
{
"route": "/assets/*",
"headers": { "Cache-Control": "public, max-age=31536000, immutable" }
}
],
"globalHeaders": { "Cache-Control": "no-cache" }
}
no-cache does not mean "do not store". It means the browser must check with the server before reusing its copy, so index.html always points at the current hashed files.
In the same change I added a small Vite plugin that runs after the bundle is written and merges security headers into that config file: a Content-Security-Policy whose connect-src is built from the build's own API and monitoring origins, Referrer-Policy: same-origin so an address holding a patient search is never sent to another site, X-Frame-Options: DENY, and Strict-Transport-Security. The same function feeds vite preview, so a policy violation shows up locally. That is what the build writes into the file; I am not describing a live deployment here.
Trade-offs of memory-only caching
- A page reload starts from nothing. With no persisted cache, every reload shows skeletons once.
no-storegives up HTTP revalidation. Every background refetch downloads the full response, since the browser keeps no copy to validate against.- The cache reset is all or nothing. Any change of admin id clears every query, including lists that hold no patient data.
- The audited record can be stale. With all three automatic refetches off, an open drawer shows what it loaded. The hook still exposes
refetch, and mutations either patch the cached copy or invalidate its tag. - Opt-outs live on the hook. A new screen that reads the detail has to repeat the three options, so the rule is in the project notes.
Takeaways
- Decide where sensitive responses may live first: here, JavaScript memory only, with
cache: 'no-store'on the base query. refetchOnMountOrArgChangewith a number of seconds gives stale-while-revalidate for every list in one line.- Set
keepUnusedDataForper endpoint instead of raising it globally. - When a read has a side effect such as an audit entry, turn off every automatic refetch for it and patch the cache after mutations.
- Reset the API cache whenever the signed-in user's id changes, not only on an explicit sign-out.