MENU
Unsubscribing
When all the components that subscribe to a query have been unmounted, the cache entry associated with the query is removed after some time (default to 60s).
Consider this:
Below, if 'conditionA' is true, three cache entries will be created (for useGetUserQuery(1), useGetUserQuery(2), and useGetUserQuery(3)). If at a later stage, 'conditionB' becomes true instead, the three cache entries will persist even when one of the components has unsubsribed. If, later, only 'conditionC' is true, one of the three cache entries (for useGetUserQuery(3)) will be removed after 60s, as the subscription reference count for the cache entry has dropped to zero.
function ComponentOne() {
const { data } = useGetUserQuery(1); // component subscribes to the data
return <div>...</div>
}
function ComponentTwo() {
const { data } = useGetUserQuery(2); // component subscribes to the data
return <div>...</div>
}
function ComponentThree() {
const { data } = useGetUserQuery(3); // component subscribes to the data
return <div>...</div>
}
function ComponentFour() {
const { data } = useGetUserQuery(3); // component subscribes to the *same* data as ComponentThree, as it has the same query parameters
return <div>...</div>
}
function App(){
...
if (conditionA) return (<div>
<ComponentOne/>
<ComponentTwo/>
<ComponentThree/>
<ComponentFour/>
</div>);
if (conditionB) return (<div>
<ComponentOne/>
<ComponentTwo/>
<ComponentThree/>
</div>);
if (conditionC) return (<div>
<ComponentOne/>
<ComponentTwo/>
</div>);
}
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:
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
export const api = createApi({
baseQuery: fetchBaseQuery({ baseUrl: '/' }),
// global configuration for the api
keepUnusedDataFor: 30,
endpoints: (builder) => ({
getPosts: builder.query({
query: () => `posts`,
// configuration for an individual endpoint, overriding the api setting
keepUnusedDataFor: 5,
}),
}),
})