RTK Query providesTags and invalidatesTags: how do they work?
IntermediateState management interview questionBy UIRound, updated 24 November 2026
Short answer
In RTK Query, providesTags on a query endpoint attaches tags such as { type: "Post", id: 5 } to the data it cached. invalidatesTags on a mutation endpoint lists the tags that mutation makes stale. When the mutation finishes, every cache entry that provided a matching tag is refetched if a component is still subscribed to it, or removed from the cache if nothing is. You declare the relationships; RTK Query works out what to refetch.
The wider picture of createApi, hooks and cache keys is in what is RTK Query and how does it work. This page is only about tags.
Declaring tag types on createApi
Tag types are declared once, in tagTypes. A tag is either a string, "Post", or an object with a type and an optional id, { type: "Post", id: 5 }. Ids can be strings or numbers.
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
type Post = { id: number; title: string; authorId: number };
export const api = createApi({
reducerPath: "api",
baseQuery: fetchBaseQuery({ baseUrl: "/api" }),
tagTypes: ["Post", "User"],
endpoints: (build) => ({
// endpoints below
}),
});With TypeScript, using a tag type that is not in tagTypes is a type error, which catches typos that would otherwise silently never match. When you add endpoints from another file with injectEndpoints and need a new tag type, add it with api.enhanceEndpoints({ addTagTypes: ["Comment"] }).
providesTags is only for query endpoints and invalidatesTags only for mutation endpoints. A query cannot invalidate anything.
The two forms of providesTags
The array form is fixed. Every result of the endpoint gets the same tags:
getStats: build.query<Stats, void>({
query: () => "stats",
providesTags: ["Post"],
}),The function form receives (result, error, arg) and returns an array, so tags can depend on the data. It also receives a fourth meta argument, which is rarely needed.
getPost: build.query<Post, number>({
query: (id) => `posts/${id}`,
providesTags: (result, error, id) => [{ type: "Post", id }],
}),
getPosts: build.query<Post[], void>({
query: () => "posts",
providesTags: (result) =>
result
? [...result.map(({ id }) => ({ type: "Post" as const, id })), { type: "Post", id: "LIST" }]
: [{ type: "Post", id: "LIST" }],
}),getPost uses arg, the id it was called with, so its tag exists even when the request fails. getPosts provides one tag per post it returned, plus a LIST tag for the collection as a whole. The as const keeps "Post" as a literal type inside map.
Why result can be undefined
The function form runs after every request, failed ones included. The docs say that either result or error may be undefined depending on whether the query succeeded. So this throws a TypeError the first time the request fails:
providesTags: (result) => result.map(({ id }) => ({ type: "Post" as const, id })), // breaks on errorAlways handle the missing result, either with the ternary above or a default parameter, (result = []) =>.
What you return on error matters too. If a failed getPosts provides nothing, no mutation can ever invalidate it, so it stays in its error state until something calls refetch(). Returning the LIST tag on error means the next add or delete retries it. The docs take this further with error tags: a query that fails with a 401 provides an "UNAUTHORIZED" tag, and a successful login mutation invalidates it, so every query that failed for lack of auth refetches.
invalidatesTags on mutations
invalidatesTags takes the same shapes. The function form receives (result, error, arg), where arg is what you passed to the mutation trigger:
addPost: build.mutation<Post, Omit<Post, "id">>({
query: (body) => ({ url: "posts", method: "POST", body }),
invalidatesTags: [{ type: "Post", id: "LIST" }],
}),
updatePost: build.mutation<Post, Pick<Post, "id"> & Partial<Post>>({
query: ({ id, ...patch }) => ({ url: `posts/${id}`, method: "PATCH", body: patch }),
invalidatesTags: (result, error, { id }) => [{ type: "Post", id }],
}),
deletePost: build.mutation<void, number>({
query: (id) => ({ url: `posts/${id}`, method: "DELETE" }),
invalidatesTags: (result, error, id) => [{ type: "Post", id }],
}),The function also runs when the mutation fails with an error from the base query, such as an HTTP error from fetchBaseQuery. If a failed update should not trigger a refetch, return [] when error is set.
How matching works
The rules are short:
- A general tag,
"Post"or{ type: "Post" }, invalidates every provided tag of that type, with or without an id. - A specific tag,
{ type: "Post", id: 5 }, invalidates only entries that provided that exact type and id. It does not match an entry that provided only the general"Post"tag.
Applied to the endpoints above:
| Mutation | Invalidates | Refetches |
|---|---|---|
addPost |
{ Post, LIST } |
getPosts only. No getPost(id) entry provides LIST. |
updatePost(5) |
{ Post, 5 } |
getPost(5), and getPosts because the list contains post 5 and provided its tag |
deletePost(5) |
{ Post, 5 } |
The same two. A mounted getPost(5) will now fail, which is expected |
Anything with "Post" |
Every Post tag |
Every post query in the cache |
LIST is not special to RTK Query. It is an id you chose, and the only rule is that it must never collide with a real id from your data. A post whose id is the string "LIST" would break the pattern.
How fine-grained to make tags
- Per id for anything that changes one entity: update, delete, like. It refetches only entries that contain that entity.
- LIST for changes to membership: create, or anything that changes which items a list query would return. A new post has no id the list could have provided yet, so only a collection tag can reach the list.
- The whole type only when a change really affects every entry, such as a bulk import or a reorder. It is easy to write and expensive at runtime: every mounted post query refetches.
Tags can cross types. If posts show their author's name, updateUser can invalidate [{ type: "User", id }, { type: "Post", id: "LIST" }]. Or the post list can provide User tags for its authors, which is more precise but easy to get wrong.
Filtered or paginated lists are separate cache entries, one per argument. If each provides { Post, LIST }, an add refetches every page or filter that is mounted. That is usually right, because the new item could belong on any of them. For very large caches, provide a narrower id per list, such as `LIST-${status}`, and invalidate only the lists the mutation can affect.
Invalidating by hand with api.util.invalidateTags
Sometimes the change does not come from an RTK Query mutation: a websocket message, a form that posts through a thunk, or another tab. Dispatch the action yourself:
socket.addEventListener("message", (event) => {
const msg = JSON.parse(event.data);
if (msg.type === "post-updated") {
store.dispatch(api.util.invalidateTags([{ type: "Post", id: msg.id }]));
}
});It follows the same matching rules as a mutation. To see what a set of tags would hit without invalidating anything, api.util.selectInvalidatedBy(state, tags) returns the matching endpoint names, arguments and cache keys, which helps when debugging an over-eager refetch.
Only subscribed queries refetch
Invalidation does not fetch everything that matches. For each matching cache entry, RTK Query checks whether any component or initiate() call is subscribed to it:
- Subscribed: the query refetches. The hook keeps showing the old
datawithisFetchingtrue, so the screen does not flash a loading state. - Not subscribed: the entry is removed from the cache, even if
keepUnusedDataFor(60 seconds by default) has not run out. The next component to mount fetches fresh data instead of showing a stale copy.
Timing is controlled by invalidationBehavior on createApi. The default, "delayed", waits until all running queries and mutations have settled, then applies the invalidations together. Two mutations running at the same time therefore cause one refetch per query, not two. The docs note the cost: if requests are always running, invalidation can be delayed indefinitely. "immediately" applies each invalidation as soon as its mutation finishes.
You can practise building this logic, including the subscribed-only rule and the delayed batch, in RTK Query-style cache tags.
Follow-up questions interviewers ask
Why does the list refetch when I update one post?
Because the list provided a { type: "Post", id } tag for every post it returned, and the update invalidated one of them. That is the point of providing per-item tags on lists: the list is refreshed whenever any item in it changes.
Tags refetch, but can I avoid the network request?
Yes. Update the cache directly with api.util.updateQueryData in onQueryStarted for an optimistic update, or write the mutation's response into the cache when it arrives. Skip invalidatesTags for that entry, or keep it as a safety net. The optimistic version is shown on the RTK Query overview.
What happens if a query provides no tags at all?
Nothing can invalidate it. It refetches only through refetch(), polling, refetchOnMountOrArgChange, focus or reconnect refetching, or when its argument changes.
How is this different from TanStack Query's invalidateQueries?
TanStack Query invalidates by query key prefix: you name the queries. RTK Query invalidates by tags: queries describe their data and mutations describe what they changed, so neither needs to know the other's cache keys. RTK Query vs TanStack Query covers the rest, and a mini React Query with prefix invalidation lets you build the key-based version.
How do you reset all cached data on logout?
Invalidating every type would refetch everything that is mounted, possibly with the old user's credentials. Dispatch api.util.resetApiState() instead, which clears the whole API slice.
Sources
Practise it in code
Interviewers rarely stop at the definition. These questions open in an editor with tests.
- Build RTK Query-style cache tags:
providesTags,invalidatesTagsand refetching only subscribed queriesMedium50 min - Build a mini React Query:
QueryClient,useQuery, prefix invalidation and garbage collectionHard60 min - Build a TanStack Query-style
useMutation(): lifecycle callbacks, optimistic updates, rollback and invalidationMedium50 min - Build a data browser over a remote API: a shared cache, deduplicated requests, prefetch and no stale dataMedium45 min