Cache Invalidation and Tag-Based Refetching
What you'll learn: How RTK Query automatically refreshes your data when something changes, using a powerful tagging system.
The Two Hardest Problems
There's an old joke in programming: "There are only two hard things in Computer Science: cache invalidation and naming things." RTK Query solves the first one elegantly with tags.
The Core Idea
When you fetch data, you "tag" it with labels like 'Post' or 'User'. When you mutate data (create, update, delete), you tell RTK Query which tags are now "invalid." RTK Query then automatically refetches any queries that provided those tags.
Think of it like a library card catalog: when you check out a book (query data), you attach a subject tag. When someone adds new books to that subject (mutation), the librarian rings a bell, and everyone with that subject tag knows to check the catalog again.
How It Works
In your API definition:
endpoints: (builder) => ({
getPosts: builder.query({
query: () => '/posts',
providesTags: ['Post'] // This query provides 'Post' data
}),
addPost: builder.mutation({
query: (newPost) => ({
url: '/posts',
method: 'POST',
body: newPost
}),
invalidatesTags: ['Post'] // This mutation makes 'Post' stale
})
})
When addPost completes successfully, RTK Query sees the 'Post' tag is invalidated and automatically re-runs getPosts in any component currently using it.
Key Takeaway: RTK Query's providesTags and invalidatesTags create an automatic refetching system—queries declare what data they provide, mutations declare what they invalidate, and fresh data flows without manual coordination.