Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 41 ยท Async Logic and Data Fetching

RTK Query Basics

Learn RTK Query: createApi, endpoints, auto-generated hooks, cache keys, reference counting and refetching, with a runnable cache stand-in that shows the core idea.

Fetching data by hand means writing the same things again and again: a thunk, three actions, a status field, error handling, and logic to avoid asking for the same data twice. RTK Query is the data-fetching and caching layer built into Redux Toolkit. You describe your endpoints once and it gives you a reducer, middleware and React hooks that handle loading states, caching, deduplication and refetching.

It does not replace Redux: its cache lives in your normal store, so you see every request in the Redux DevTools like any other action.

RTK Query is not available in the live editors here. The real API is shown in read-only blocks. The runnable example is a hand-written stand-in for the central idea, a cache keyed by endpoint plus arguments with subscriber counting, so you can see why it avoids duplicate requests.

Defining an API

An API slice is created once with createApi. It needs a baseQuery (how to talk to the server) and a list of endpoints.

JavaScript
// Real Redux Toolkit code (read-only)
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

export const api = createApi({
  reducerPath: 'api',
  baseQuery: fetchBaseQuery({ baseUrl: '/api' }),
  endpoints: (build) => ({
    getPosts: build.query({
      query: () => '/posts',
    }),
    getPost: build.query({
      query: (id) => `/posts/${id}`,
    }),
  }),
});

export const { useGetPostsQuery, useGetPostQuery } = api;

Then add the generated reducer and middleware to the store:

JavaScript
// Real Redux Toolkit code (read-only)
import { configureStore } from '@reduxjs/toolkit';

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

The middleware is not optional: it manages cache lifetimes, polling and invalidation. Forgetting it is the most common setup error, and RTK Query warns about it in development.

Using the hooks

JSX
// Real React + RTK Query code (read-only)
function PostList() {
  const { data: posts = [], isLoading, isFetching, isError, error, refetch } = useGetPostsQuery();

  if (isLoading) return <p>Loading...</p>;
  if (isError) return <p>Failed: {String(error.status)}</p>;
  return (
    <>
      <button onClick={refetch} disabled={isFetching}>Refresh</button>
      <ul>{posts.map((p) => <li key={p.id}>{p.title}</li>)}</ul>
    </>
  );
}

The important flags:

Flag Meaning
isLoading First load: there is no data yet
isFetching A request is running (also true during refetches, when old data is still shown)
isSuccess / isError The last request finished successfully / failed
isUninitialized The query was skipped (skip: true)
data The latest successful result, kept while refetching
currentData Data for the current arguments only (empty while arguments change)

Passing an argument is just useGetPostQuery(id). Pass skip when an argument is not ready yet: useGetPostQuery(id, { skip: !id }).

The idea: a cache keyed by endpoint and arguments

Every query result is stored under a cache key made from the endpoint name and its serialized arguments, e.g. getPost(3). When two components call useGetPostQuery(3), they share one entry and trigger one request. Each component is a subscriber; when the last one unmounts, the entry stays for keepUnusedDataFor seconds (60 by default) and is then removed.

flowchart LR
  A["Component A<br/>useGetPostQuery(3)"] --> K["cache key<br/>getPost(3)"]
  B["Component B<br/>useGetPostQuery(3)"] --> K
  K --> R["one request"]
  K --> D["shared data"]
  C["Component C<br/>useGetPostQuery(4)"] --> K2["cache key<br/>getPost(4)"]

Same endpoint and arguments share one cache entry and one request.

Here is that idea in code. Three "components" ask for the same post, and a fourth asks for another one.

JS A cache keyed by endpoint and args

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

No output.

You see two network requests for four subscriptions, and a re-subscription within the retention window costs nothing. The real library adds far more (status flags, abort, polling, refetch on focus, tag invalidation), but the principle is this table of entries.

Cache lifetime and refetching options

These can be set on createApi (as defaults) or per endpoint or per hook call:

JavaScript
// Real Redux Toolkit code (read-only)
const { data } = useGetPostsQuery(undefined, {
  pollingInterval: 30000,        // refetch every 30 s while mounted
  refetchOnFocus: true,          // needs setupListeners(store.dispatch)
  refetchOnReconnect: true,
  refetchOnMountOrArgChange: 60, // refetch if cached data is older than 60 s
});

keepUnusedDataFor controls how long unused data lingers. A short value saves memory, a long one makes back-navigation instant. For data that must always be fresh, combine a small value with refetchOnMountOrArgChange: true.

Transforming and selecting

transformResponse reshapes a response before it is cached (for example, to an id-indexed object), and the hook's selectFromResult option lets a component subscribe to just the part it needs so it does not re-render for unrelated changes. Data in the cache is read-only; to change it, use a mutation or updateQueryData.

RTK Query or createAsyncThunk?

Use RTK Query for server state (data that lives on a server and can become stale). Use plain slices, thunks and listeners for client state and workflows that are not "fetch and cache". A page often uses both, and they sit side by side in one store.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What do two components share when both call useGetPostQuery(3)?

    The cache key is endpoint plus serialized arguments, so both read the same entry.
  2. 2. What is the difference between isLoading and isFetching?

    During a refetch, data is kept, so isLoading is false but isFetching is true.
  3. 3. What happens if you forget to add api.middleware to the store?

    The middleware drives the cache lifecycle; RTK Query logs a warning in development.
  4. 4. What does keepUnusedDataFor control?

    The default is 60 seconds.

Summary

  • createApi defines endpoints; the generated reducer and middleware go into the store.
  • Hooks such as useGetPostsQuery give data, isLoading, isFetching and error.
  • Results are cached by endpoint plus arguments; subscribers share one request.
  • Unused entries are removed after keepUnusedDataFor seconds.
  • Use skip, polling and refetch options to control freshness.

Next: RTK Query mutations and tags