← Back to React, page 4

react-0073 · Medium mid

What is RTK Query, how do endpoints, generated hooks and tag invalidation work, and when do you pick it over TanStack Query?

RTK Query is the data fetching and caching tool inside Redux Toolkit. createApi defines endpoints (queries that read and mutations that write), and it generates hooks such as useGetStudentsQuery. Cache entries are keyed by endpoint and arguments. Queries declare providesTags, mutations declare invalidatesTags, and a matching mutation makes the right queries refetch. Choose it when the app already uses Redux Toolkit.

Full answer

RTK Query solves the same problem as TanStack Query: server state, caching, deduplication and loading flags. It lives in the Redux store, so the cache is visible in devtools and fits an existing Redux setup.

You define an API slice once with createApi. It takes a reducerPath, a baseQuery (usually fetchBaseQuery({ baseUrl }), or a custom function) and endpoints. Each endpoint is build.query for reads or build.mutation for writes. RTK Query generates hooks from the endpoint names: useGetStudentsQuery(args) and useAddStudentMutation().

The cache key is the endpoint name plus the serialized arguments. Two components calling useGetStudentQuery(5) share one request and one entry. Unused entries are removed after keepUnusedDataFor seconds (60 by default).

Tags connect reads and writes. A query declares providesTags: ['Student'] and a mutation declares invalidatesTags: ['Student']. When the mutation finishes, every active query that provides that tag refetches. Tags can include ids, such as { type: 'Student', id: 5 }, for fine-grained updates.

Setup needs the API reducer under api.reducerPath and api.middleware added to the store. The middleware handles caching, polling and invalidation.

Hooks return data, isLoading (first load), isFetching (any request), isError and error. Options include skip, pollingInterval and selectFromResult to avoid extra re-renders. For optimistic updates use onQueryStarted and updateQueryData.

Compared with TanStack Query: RTK Query is tied to Redux and comes with codegen from OpenAPI and good typing from endpoint definitions. TanStack Query works without Redux and has a larger ecosystem of patterns. If Redux is already in the project, RTK Query is the natural choice. If not, TanStack Query is lighter to adopt.

The example uses a custom baseQuery with in-memory data so it runs without a network.

jsx
import { configureStore } from '@reduxjs/toolkit';
import { createApi } from '@reduxjs/toolkit/query/react';
import { Provider } from 'react-redux';

let students = ['Asha', 'Ravi'];

const api = createApi({
  reducerPath: 'api',
  baseQuery: async ({ method = 'GET', body }) => {
    await new Promise((resolve) => setTimeout(resolve, 20));
    if (method === 'POST') students = [...students, body.name];
    return { data: [...students] };
  },
  tagTypes: ['Student'],
  endpoints: (build) => ({
    getStudents: build.query({
      query: () => ({ url: '/students' }),
      providesTags: ['Student'],
    }),
    addStudent: build.mutation({
      query: (name) => ({ url: '/students', method: 'POST', body: { name } }),
      invalidatesTags: ['Student'],
    }),
  }),
});

const { useGetStudentsQuery, useAddStudentMutation } = api;

const store = configureStore({
  reducer: { [api.reducerPath]: api.reducer },
  middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
});

function Students() {
  const { data, isLoading } = useGetStudentsQuery();
  const [addStudent] = useAddStudentMutation();

  if (isLoading) return <p>Loading...</p>;

  return (
    <div>
      <ul>
        {data.map((name) => (
          <li key={name}>{name}</li>
        ))}
      </ul>
      <button onClick={() => addStudent('Meera')}>Add Meera</button>
    </div>
  );
}

export default function App() {
  return (
    <Provider store={store}>
      <Students />
    </Provider>
  );
}

This ran against a custom baseQuery and in-memory data. The check waited for the first load, pressed Add Meera and waited for the tag invalidation to refetch. Output of the run: after first load: AshaRaviAdd Meera after mutation and automatic refetch: AshaRaviMeeraAdd Meera

Key points

  • createApi defines endpoints and generates typed hooks.
  • The cache key is the endpoint plus its arguments, and requests are deduplicated.
  • providesTags and invalidatesTags drive automatic refetching after mutations.
  • The API reducer and middleware must be added to the store.
  • Pick it when Redux Toolkit is already in use. TanStack Query suits apps without Redux.

Common mistakes

  • Forgetting to add api.middleware to the store, so caching and invalidation do not work.
  • Mixing up isLoading and isFetching.
  • Skipping tags, so the list does not refresh after a mutation.
  • Putting the API data into another slice and keeping two copies.
  • Creating many small APIs instead of one API slice per backend.

Follow-ups

  • How would you do an optimistic update with onQueryStarted?
  • How do you inject endpoints from several files into one API?
  • What does selectFromResult do?

Tips

  • Compare with TanStack Query honestly. Both are good, and the decision depends on Redux.
  • Explain tags as the link between reads and writes.
  • Mention that the middleware is required.