Cache Behavior
A key feature of RTK Query is its management of cached data. When data is fetched from the server, RTK Query will store the data in the Redux store as a 'cache'. When an additional request is performed for the same data, RTK Query will provide the existing cached data rather than sending an additional request to the server.
This page covers what RTK Query stores, and how long it keeps unused data. For when RTK Query starts a request, reuses cached data, or refetches, see Request Behavior.
Default Cache Behavior
With RTK Query, caching is based on:
- API endpoint definitions
- The serialized query parameters used when components subscribe to data from an endpoint
- Active subscription reference counts
When a subscription is started, the parameters used with the endpoint are serialized and stored internally as a queryCacheKey for the request. Any future request that produces the same queryCacheKey (i.e. called with the same parameters, factoring serialization) will be de-duped against the original, and will share the same data and updates. i.e. two separate components performing the same request will use the same cached data.
When a request is attempted, if the data already exists in the cache, then that data is served and no new request is sent to the server. Otherwise, if the data does not exist in the cache, then a new request is sent, and the returned response is stored in the cache.
Subscriptions are reference-counted. Additional subscriptions that ask for the same endpoint+params increment the reference count. As long as there is an active 'subscription' to the data (e.g. if a component is mounted that calls a useQuery hook for the endpoint), then the data will remain in the cache. Once the subscription is removed (e.g. when last component subscribed to the data unmounts), after an amount of time (default 60 seconds), the data will be removed from the cache. The expiration time can be configured with the keepUnusedDataFor property for the API definition as a whole, as well as on a per-endpoint basis.
Cache lifetime & subscription example
Imagine an endpoint that expects an id as the query param, and 4 components mounted which are requesting data from this same endpoint:
import { useGetUserQuery } from './api.ts'
function ComponentOne() {
// component subscribes to the data
const { data } = useGetUserQuery(1)
return <div>...</div>
}
function ComponentTwo() {
// component subscribes to the data
const { data } = useGetUserQuery(2)
return <div>...</div>
}
function ComponentThree() {
// component subscribes to the data
const { data } = useGetUserQuery(3)
return <div>...</div>
}
function ComponentFour() {
// component subscribes to the *same* data as ComponentThree,
// as it has the same query parameters
const { data } = useGetUserQuery(3)
return <div>...</div>
}
While four components are subscribed to the endpoint, there are only three distinct combinations of endpoint + query parameters. Query parameters 1 and 2 will each have a single subscriber, while query parameter 3 has two subscribers. RTK Query will make three distinct fetches; one for each unique set of query parameters per endpoint.
Data is kept in the cache as long as at least one active subscriber is interested in that endpoint + parameter combination. When the subscriber reference count reaches zero, a timer is set, and if there are no new subscriptions to that data by the time the timer expires, the cached data will be removed. The default expiration is 60 seconds, which can be configured both for the API definition as a whole, as well as on a per-endpoint basis.
If 'ComponentThree' is unmounted in the example above, regardless of how much time passes, the data will remain in the cache due to 'ComponentFour' still being subscribed to the same data, and the subscribe reference count will be 1. However, once 'ComponentFour' unmounts, the subscriber reference count will be 0. The data will remain in the cache for the remainder of the expiration time. If no new subscription has been created before the timer expires, the cached data will finally be removed.
How long unused data is kept
When an entry loses its last subscriber, RTK Query starts a timer. When the timer runs out and the entry still has no subscribers, the entry is removed. A new subscriber before then cancels the removal.
| Option | Where it is set | Values | Default |
|---|---|---|---|
keepUnusedDataFor | createApi, endpoint definition | seconds, or Infinity | 60 |
retainFor | initiate() options | seconds | not set |
keepUnusedDataFor is a memory setting. It controls how long unused data stays in the store. It does not decide when data refetches. For that, see Request Behavior.
keepUnusedDataFor
The endpoint's value overrides the createApi value:
- TypeScript
- JavaScript
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
import type { Post } from './types'
export const api = createApi({
baseQuery: fetchBaseQuery({ baseUrl: '/' }),
// global configuration for the api
keepUnusedDataFor: 30,
endpoints: (build) => ({
getPosts: build.query<Post[], void>({
query: () => `posts`,
// configuration for an individual endpoint, overriding the api setting
keepUnusedDataFor: 5,
}),
}),
})
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
export const api = createApi({
baseQuery: fetchBaseQuery({ baseUrl: '/' }),
// global configuration for the api
keepUnusedDataFor: 30,
endpoints: (build) => ({
getPosts: build.query({
query: () => `posts`,
// configuration for an individual endpoint, overriding the api setting
keepUnusedDataFor: 5,
}),
}),
})
Infinitykeeps unused entries until something removes them. Very large values are capped at about 24 days.- The timer also restarts when a request for an unused entry finishes, and when
upsertQueryEntrieswrites the entry. It does not restart when asubscribe: falsecall is served from the cache, unless that call passesretainFor.
retainFor
retainFor keeps one entry longer without changing the endpoint. The entry is kept for the longer of keepUnusedDataFor and retainFor. For a running subscribe: false request, the time counts from when the request finishes.
Use it when you load data before the component that reads it mounts, for example in a router loader:
// In a route loader: fetch now, keep the data for at least 30 seconds
await store.dispatch(
api.endpoints.getPost.initiate(id, { subscribe: false, retainFor: 30 }),
)
Removing data earlier
These remove entries before the timer runs out:
| Cause | What is removed |
|---|---|
| Tag invalidation | invalidated entries with no subscribers |
| Focus or reconnect | entries that were requested but have no subscribers now, when the createApi refetchOnFocus / refetchOnReconnect value allows a refetch |
api.util.removeQueryData | one entry, even if it has subscribers (unless onlyIfUnused: true) |
reset() from a lazy query hook | that hook's entry |
api.util.resetApiState | everything |
Tag invalidation and focus refetch entries that have subscribers, and remove entries that don't. Refetching data nobody is using would waste a request, so RTK Query drops it instead. The next subscriber fetches it again.
removeQueryData also aborts a running request for the entry. Mounted useQuery hooks for that entry fetch it again and show isLoading: true.
Watching a query outside components
A listener or store.subscribe callback does not hold a subscription. If nothing else uses the entry, it is removed after keepUnusedDataFor. To keep the entry alive and refetching, hold a subscription with initiate() and read the data with select():
const subscription = store.dispatch(api.endpoints.getPosts.initiate())
const selectPosts = api.endpoints.getPosts.select()
const unsubscribeStore = store.subscribe(() => {
const { data, status } = selectPosts(store.getState())
// react to the latest data
})
// When finished:
subscription.unsubscribe()
unsubscribeStore()
The subscription makes the entry eligible for the same refetches as a mounted hook. Tag invalidation refetches it. Polling needs a pollingInterval in the initiate() subscription options, and focus or reconnect refetches need refetchOnFocus / refetchOnReconnect plus setupListeners.
Refreshing cached data
By default, cached data is reused until it is removed. RTK Query can also refetch it: on demand with refetch(), when a component mounts, on window focus or network reconnect, on a polling timer, or after a mutation invalidates its tags. Request Behavior covers each of these and how they combine.
Tradeoffs
No Normalized or De-duplicated Cache
RTK Query deliberately does not implement a cache that would deduplicate identical items across multiple requests. There are several reasons for this:
- A fully normalized shared-across-queries cache is a hard problem to solve
- We don't have the time, resources, or interest in trying to solve that right now
- In many cases, simply re-fetching data when it's invalidated works well and is easier to understand
- At a minimum, RTKQ can help solve the general use case of "fetch some data", which is a big pain point for a lot of people
As an example, say that we have an API slice with getTodos and getTodo endpoints, and our components make the following queries:
getTodos()getTodos({filter: 'odd'})getTodo({id: 1})
Each of these query results would include a Todo object that looks like {id: 1}.
In a fully normalized de-duplicating cache, only a single copy of this Todo object would be stored. However, RTK Query saves each query result independently in the cache. So, this would result in three separate copies of this Todo being cached in the Redux store. However, if all the endpoints are consistently providing the same tags (such as {type: 'Todo', id: 1}), then invalidating that tag will force all the matching endpoints to refetch their data for consistency.
The Redux docs have always recommended keeping data in a normalized lookup table to enable easily finding items by ID and updating them in the store, and RTK's createEntityAdapter was designed to help manage normalized state. Those concepts are still valuable and don't go away. However, if you're using RTK Query to manage caching data, there's less need to manipulate the data that way yourself.
There are a couple additional points that can help here:
- The generated query hooks have a
selectFromResultoption that allow components to read individual pieces of data from a query result. As an example, a<TodoList>component might calluseTodosQuery(), and each individual<TodoListItem>could use the same query hook but select from the result to get the right todo object. - You can use the
transformResponseendpoint option to modify the fetched data so that it's stored in a different shape, such as usingcreateEntityAdapterto normalize the data for this one response before it's inserted into the cache.
Further information
Examples
Cache Subscription Lifetime Demo
This example is a live demo of how the subscriber reference count and the value of keepUnusedDataFor interact with each other. The Subscriptions and Queries (including the cached data) are shown in the demo for you to visualize (note that this can also be viewed in the Redux Devtools Extension).
Two components are mounted, each with the same endpoints query (useGetUsersQuery(2)). You will be able to observe that when toggling off the components, the subscriber reference count will be reduced. After toggling off both components such that the subscriber reference count reaches zero, you will observe the cached data under the Queries section will persist for 5 seconds (the value of keepUnusedDataFor provided for the endpoint in this demo). If the subscriber reference count remains at 0 for the full duration, the cached data will then be removed from the store.