If you are wondering how to clear RTK Query cache, the best method depends on whether you want to reset the entire API cache, refresh particular data, or simply let unused entries expire. RTK Query stores server responses in Redux state and reuses them to avoid unnecessary network requests. That behavior is usually helpful, but during logout, account changes, testing, or troubleshooting, you may need to remove or refresh cached data.
In most cases, use api.util.resetApiState() to clear every cache entry managed by an API slice, or invalidate tags to refresh specific data. This guide explains both approaches, shows when to use them, and covers common mistakes that can make cache clearing seem ineffective.
How RTK Query Cache Works
RTK Query keeps query results in your Redux store. A cache entry is associated with an endpoint and its serialized arguments. For example, calls to getUser(12) share a cache entry when they use the same API slice and equivalent arguments. Components that subscribe to that query can reuse the result instead of requesting the same data again.
Cache entries are not necessarily deleted as soon as a component unmounts. By default, RTK Query keeps an unused entry for a period of time, controlled by keepUnusedDataFor. If a component subscribes again before that period ends, it can receive the cached result. This is expected behavior, not a sign that cache clearing failed.
Clear the Entire RTK Query Cache
To reset all query and mutation state for an API slice, dispatch its resetApiState action:
import { api } from './services/api'
// Clear all cache entries managed by this API slice
dispatch(api.util.resetApiState())
This resets the state managed by that API slice, including its cached query results. It is useful when a user signs out, when the active account changes, or when you need a clean slate in a test. If your application has multiple API slices, reset each one that contains data you want to clear.
For example, a logout handler might look like this:
const handleLogout = () => {
dispatch(api.util.resetApiState())
dispatch(logout())
}
Make sure the api variable refers to the same API slice that is registered in your Redux store. Resetting a different API slice will not clear the cache you are viewing. Also consider the order of logout actions and any in-flight requests: if requests can still complete using the old user’s credentials, stop or guard those requests as appropriate for your application.
Clear RTK Query Cache on Logout
Clearing cached data on logout is a common security and data-isolation measure, particularly in applications where different users may sign in on the same device. Resetting the API state prevents the next user from seeing query results that were fetched during the previous session.
Dispatch the reset action as part of the logout flow, rather than relying on a page reload. A reload may not clear Redux state if the store is persisted, and it does not address cached data held by the running application. If you persist Redux state to local storage or another storage layer, also review that persistence setup. RTK Query cache is normally intended to live in memory; persisting it can introduce stale-data or account-isolation concerns.
If your application uses more than one API slice, clear every relevant slice:
dispatch(usersApi.util.resetApiState())
dispatch(adminApi.util.resetApiState())
dispatch(logout())
Refresh Specific Data with Tag Invalidation
You usually do not need to clear the entire cache to update one piece of data. RTK Query’s recommended approach is to invalidate tags. Queries can provide tags, and mutations can invalidate them. When a tag is invalidated, an actively subscribed query associated with that tag is refetched. An invalidated query with no active subscriptions can be removed instead of immediately refetched.
export const api = createApi({
reducerPath: 'api',
baseQuery: fetchBaseQuery({ baseUrl: '/api' }),
tagTypes: ['Post'],
endpoints: (builder) => ({
getPost: builder.query({
query: (id) => `posts/${id}`,
providesTags: (result, error, id) => [{ type: 'Post', id }],
}),
}),
})
To invalidate a particular post from an event handler, dispatch:
dispatch(api.util.invalidateTags([{ type: 'Post', id: 42 }]))
To invalidate all cached queries that provide the Post tag, use:
dispatch(api.util.invalidateTags(['Post']))
Tag invalidation is often the right choice after a mutation or when data may have changed on the server. It tells RTK Query that existing results are no longer trustworthy, while allowing the library to coordinate refetching with active subscriptions.
Use Mutations to Keep Cache Data Up to Date
For regular create, update, or delete operations, configure a mutation to invalidate the tags of affected queries. This avoids manually clearing the cache after every change:
updatePost: builder.mutation({
query: ({ id, ...body }) => ({
url: `posts/${id}`,
method: 'PATCH',
body,
}),
invalidatesTags: (result, error, { id }) => [
{ type: 'Post', id },
],
})
When this mutation succeeds, RTK Query invalidates the matching post tag. A component currently using getPost(42) can then receive fresh server data through a refetch. For broader changes, such as creating a post that affects a list, invalidate a list-level tag as well. Designing tags around the data your queries provide is usually more maintainable than resetting the whole API after every mutation.
Clear One Query Without Resetting Everything
RTK Query does not generally require you to manually delete an individual cache entry. If you want a particular result to become fresh, invalidate the tag provided by that query. This is safer than editing internal Redux state because it preserves RTK Query’s subscription and refetch behavior.
If the query is still mounted and subscribed, invalidating its tag typically triggers a request for updated data. If it is no longer subscribed, RTK Query can remove the invalidated entry. Check that the query actually provides the tag you are invalidating; a tag mismatch means the query will not be affected.
If your goal is simply to make a request again without clearing other entries, you can also use the query hook’s refetch function or initiate the query with a force-refetch option, depending on how you are using RTK Query. Refetching requests fresh data but is not the same as resetting all cached state.
Let Unused Cache Entries Expire
When a component stops using a query, RTK Query starts the unused-cache timer. You can adjust how long entries remain available by setting keepUnusedDataFor on an endpoint or on the API slice. The value is measured in seconds.
getProducts: builder.query({
query: () => 'products',
keepUnusedDataFor: 10,
})
In this example, an unused products cache entry is kept for 10 seconds. Once the timer expires, RTK Query can remove it. Setting this value lower can reduce how long unused data remains in memory, but it does not immediately clear a query that still has active subscribers. Use resetApiState when you need an immediate API-wide reset, or tag invalidation when you need to refresh targeted data.
Clear Cache When Query Arguments Change
RTK Query uses endpoint names and serialized query arguments to determine cache identity. Different arguments normally create separate entries. For example, getPost(1) and getPost(2) do not represent the same query result. If you keep seeing unexpected data, confirm that the hook is receiving the expected arguments and that your custom serializeQueryArgs configuration is not grouping arguments together unexpectedly.
Changing a component’s local state does not clear Redux cache by itself. Instead, it may cause the hook to subscribe to a different cache entry. Likewise, clearing browser cache or cookies usually does not clear the in-memory Redux store. Identify where the data is stored before choosing a clearing method.
Common RTK Query Cache-Clearing Problems
-
The wrong API slice is reset. Each
createApicall has its own reducer and cache. Dispatch the reset action from the slice that owns the query. - The query remains active. A mounted component can immediately request data again after a reset or invalidation. A new network request does not mean the reset failed.
- Tags do not match. The invalidated tag must match a tag provided by the query, including its type and, when used, its ID.
- Data is persisted outside RTK Query. Redux persistence, component state, or another data layer can retain values independently of the RTK Query cache.
- A stale response arrives later. If a request is already in flight, its completion can affect what the UI displays. Consider how your application handles requests during logout or account changes.
-
Cache lifetime is mistaken for active data.
keepUnusedDataForapplies to unused entries. It does not automatically remove data from queries that still have subscribers.
How to Test That the Cache Was Cleared
Use the Redux DevTools to inspect the API slice state before and after dispatching resetApiState. You can also check the query hook’s status: after a reset, the query may be uninitialized until it runs again. If an active component immediately subscribes, it may start a new request and populate the cache again.
For invalidation, verify that the query provides the tag you intend to invalidate and watch the Network panel for a refetch when the query is active. In automated tests, dispatch the reset action between test cases so cached results from one test do not affect another. Tests should also account for requests that have not finished when cleanup begins.
Which Cache-Clearing Method Should You Use?
-
Clear all data for an API slice: dispatch
api.util.resetApiState(). -
Refresh data after a mutation: use
invalidatesTagson the mutation. - Refresh a particular query result: invalidate the tag that query provides, or use its refetch behavior.
-
Control how long unused results stay in memory: configure
keepUnusedDataFor. - Prevent data crossing user sessions: reset relevant API slices during logout and review any Redux persistence.
Conclusion
To clear RTK Query cache completely, dispatch api.util.resetApiState() for the API slice that owns the data. For most targeted updates, invalidate tags instead so RTK Query can remove stale entries or refetch active queries. Use keepUnusedDataFor to manage how long unused results remain cached, and check subscriptions, API-slice configuration, and persistence when results appear to return. Choosing the narrowest method that fits your goal keeps your application’s data predictable without unnecessary cache resets.
Disclaimer: Articles are written by Humans, AI or Both. Verify Important information.