Stop 10 · State Management & Data FetchingTopics · 5/8

RTK Query

Part of the MERN Stack Roadmap

In short

If your app already uses Redux Toolkit, RTK Query adds API caching without another library. You describe your endpoints once, and it generates the data fetching hooks for you.

RTK Query is Redux Toolkit's data-fetching tool. You define API endpoints once and get generated hooks with caching, loading states and automatic refetching.

The jaadu mascot pins a fresh blank chart on a train coach next to an old crossed-out one.

Think of it like this

The railway reservation chart

Book a seat and the old chart is marked out of date, so a fresh one gets printed. RTK Query works with tags the same way: when a mutation changes 'Post', every query showing posts is marked stale and refetched automatically.

Watch it happen

Tags trigger the refetch

Add form
api slice
Server
Posts list

useGetPostsQuery()

1/7The list mounts and asks for posts. This query provides the Post tag.

The big ideas

What you need to know

createApi defines endpoints

Each endpoint is a query (read) or a mutation (write), sharing a base URL set with fetchBaseQuery.

Hooks are generated

An endpoint called getPosts gives you useGetPostsQuery, ready to use in any component.

Tags keep data fresh

Queries use providesTags, mutations use invalidatesTags. Matching tags trigger an automatic refetch.

Lives in your Redux store

Add the api's reducer and middleware to configureStore, and every request shows up in Redux DevTools.

See it in code

Walk through the code

ts
1import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";2 3type Post = { id: number; title: string };4export const api = createApi({5  baseQuery: fetchBaseQuery({ baseUrl: "/api" }),6  tagTypes: ["Post"],7  endpoints: (build) => ({8    getPosts: build.query<Post[], void>({ query: () => "posts", providesTags: ["Post"] }),9    addPost: build.mutation<Post, { title: string }>({10      query: (body) => ({ url: "posts", method: "POST", body }),11      invalidatesTags: ["Post"],12    }),13  }),14});15 16export const { useGetPostsQuery, useAddPostMutation } = api;

1/5fetchBaseQuery is a small fetch wrapper with a base URL.

Once addPost succeeds, the Post tag is invalidated and getPosts refetches by itself. Remember to add api.reducer and api.middleware to your store.

Save yourself the pain

Common mistakes

Oops

Forgetting to add api.middleware to configureStore.

Do this instead

Without it, caching, invalidation and polling don't work. Use middleware: (gDM) => gDM().concat(api.middleware).

Oops

Skipping tags and calling refetch by hand after every mutation.

Do this instead

Set providesTags and invalidatesTags once. The refetching then happens on its own.

Oops

Using RTK Query and TanStack Query in one app for the same data.

Do this instead

Pick one. RTK Query if you're already on Redux, TanStack Query if you aren't.

Your mission

Posts that refresh themselves

~35 min

Quick check

addPost has invalidatesTags: ['Post'] and getPosts has providesTags: ['Post']. A user adds a post. What happens to the list?

Go deeper

  1. 1Define a productsApi with getProducts and addProduct endpoints.
  2. 2Use tags so adding a product refetches the list automatically.
  3. 3Compare the code with your hand-written useEffect fetching.

Also part of these roadmaps

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge