Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 41 ยท Async Logic and Data Fetching

RTK Query Mutations and Tags

Learn how RTK Query mutations change server data, how providesTags and invalidatesTags refetch stale queries, and how optimistic updates with rollback work.

Reading data is only half of an app. Users also create, edit and delete things, and after each change the cached lists on screen are wrong until they are refreshed. RTK Query solves this with mutations (requests that change server data) and tags (labels that tell the cache which entries a mutation makes stale).

The Redux packages are not available in the editors on this site, so the real API is shown read-only, and a runnable stand-in demonstrates the tag mechanism itself.

Mutations

A mutation endpoint is defined with build.mutation. The hook returns a trigger function and a result object, instead of fetching on mount.

JavaScript
// Real Redux Toolkit code (read-only)
export const api = createApi({
  reducerPath: 'api',
  baseQuery: fetchBaseQuery({ baseUrl: '/api' }),
  tagTypes: ['Post'],
  endpoints: (build) => ({
    getPosts: build.query({
      query: () => '/posts',
      providesTags: (result = []) => [
        ...result.map(({ id }) => ({ type: 'Post', id })),
        { type: 'Post', id: 'LIST' },
      ],
    }),
    addPost: build.mutation({
      query: (body) => ({ url: '/posts', method: 'POST', body }),
      invalidatesTags: [{ type: 'Post', id: 'LIST' }],
    }),
    updatePost: build.mutation({
      query: ({ id, ...patch }) => ({ url: `/posts/${id}`, method: 'PATCH', body: patch }),
      invalidatesTags: (result, error, { id }) => [{ type: 'Post', id }],
    }),
    deletePost: build.mutation({
      query: (id) => ({ url: `/posts/${id}`, method: 'DELETE' }),
      invalidatesTags: (result, error, id) => [{ type: 'Post', id }, { type: 'Post', id: 'LIST' }],
    }),
  }),
});

export const { useGetPostsQuery, useAddPostMutation, useUpdatePostMutation, useDeletePostMutation } = api;
JSX
// Real React code (read-only)
function NewPost() {
  const [addPost, { isLoading, error }] = useAddPostMutation();
  async function onSubmit(e) {
    e.preventDefault();
    try {
      await addPost({ title: e.target.title.value }).unwrap();
      e.target.reset();
    } catch {
      /* the `error` field also holds the failure */
    }
  }
  return (
    <form onSubmit={onSubmit}>
      <input name="title" />
      <button disabled={isLoading}>Add</button>
    </form>
  );
}

Tags: how the cache knows what to refetch

Queries provide tags, mutations invalidate them. A tag is an object { type, id } (or just a type string). When a mutation succeeds and invalidates a tag, every active query that provides that tag is refetched, and inactive ones are dropped from the cache.

Concept Set on Meaning
tagTypes createApi The list of valid tag type names
providesTags query "My data contains these things"
invalidatesTags mutation "These things changed on the server"

The special id 'LIST' is a convention for "the collection as a whole": adding or deleting an item changes the list but not other items, so a mutation invalidates {type:'Post', id:'LIST'}, and editing a single post invalidates just {type:'Post', id}.

sequenceDiagram
  participant C as Component
  participant M as Mutation
  participant Cache
  C->>M: addPost(body)
  M->>Cache: invalidate Post:LIST
  Cache->>C: refetch getPosts
  Cache-->>C: fresh list

The component never refetches by hand: the invalidated tag does it.

Tag invalidation in miniature

The stand-in below keeps a cache of queries together with the tags each one provides. A mutation calls invalidate, which finds matching entries and refetches them.

JS Tags, providing and invalidating

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first mutation refetches only the list. The second refetches post 1 and the list, because the list provides a tag for every item, so it contains Post:1. Post 2 is never refetched. Fine-grained tags are what make invalidation precise.

Optimistic updates

Waiting for the server before updating the screen feels slow. An optimistic update applies the change locally first and rolls back if the request fails. In RTK Query you do it in onQueryStarted with updateQueryData:

JavaScript
// Real Redux Toolkit code (read-only)
updatePost: build.mutation({
  query: ({ id, ...patch }) => ({ url: `/posts/${id}`, method: 'PATCH', body: patch }),
  async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {
    const undo = dispatch(
      api.util.updateQueryData('getPost', id, (draft) => {
        Object.assign(draft, patch);        // Immer draft: "mutate" it
      }),
    );
    try {
      await queryFulfilled;
    } catch {
      undo.undo();                          // roll back on failure
    }
  },
}),

updateQueryData produces patches, and undo() reverts exactly them, so other changes that happened in between are kept. For simple cases you can skip optimism and let the invalidated tag refetch.

Other useful tools

  • api.util.invalidateTags([...]) invalidates from anywhere (for example after a WebSocket message).
  • api.util.prefetch warms the cache before a navigation.
  • onCacheEntryAdded supports streaming updates: open a WebSocket when data is first requested and update the cache as messages arrive.
  • transformErrorResponse normalizes errors for the UI.
  • Code splitting: api.injectEndpoints({ endpoints }) adds endpoints from other files to one API slice, which keeps a single cache and middleware.

Common mistakes

  • Listing a tag in invalidatesTags that is not in tagTypes (a TypeScript error and a dev warning).
  • Returning no LIST tag from the list query, so adding an item never refreshes it.
  • Invalidating the whole type for small edits, which refetches more than needed.
  • Mutating data returned by a hook: it is frozen. Use updateQueryData or copy it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which side provides tags and which invalidates them?

    Queries say what their data contains; mutations say what became stale.
  2. 2. A new post is added. Which invalidation refreshes the list of posts?

    The conventional LIST tag represents the whole collection.
  3. 3. What does undo() do in an optimistic update?

    It reverses exactly those patches and keeps later changes.
  4. 4. Why is data returned by a query hook read-only?

    Mutating cached data would bypass the store. Update it through updateQueryData.

Summary

  • Mutations send changes; the hook gives a trigger function and status.
  • providesTags on queries and invalidatesTags on mutations keep the cache in sync automatically.
  • Use {type, id} tags plus a LIST tag for precise refetching.
  • Optimistic updates use onQueryStarted, updateQueryData and undo().
  • injectEndpoints splits one API across files.

Next: How middleware works