Sub topic 12
Fetching and Caching Server Data with RTK Query
This chapter assumes you can write a slice, configure a store, and use useSelector and useDispatch. It also assumes you have seen createAsyncThunk. RTK Query is a data fetching and caching tool that ships inside Redux Toolkit. It replaces the hand-written thunk, loading flags, and error fields for server data.
Why RTK Query exists
With createAsyncThunk, you write the same pieces for each request: a thunk, three extraReducers cases, and status and error fields. You also decide when to refetch and how to avoid duplicate requests. RTK Query handles these for you. It tracks loading state, caches results by request arguments, and shares one request between components that ask for the same data.
Defining an API slice
You describe the server with createApi. Each endpoint becomes a generated hook.
import { configureStore } from '@reduxjs/toolkit'
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
export const api = createApi({
reducerPath: 'api',
baseQuery: fetchBaseQuery({ baseUrl: '/api' }),
endpoints: (builder) => ({
getTodos: builder.query({
query: () => 'todos',
}),
}),
})
export const { useGetTodosQuery } = api
export const store = configureStore({
reducer: {
[api.reducerPath]: api.reducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(api.middleware),
})
// In a component:
// const { data, isLoading, error } = useGetTodosQuery()Three parts connect the API to the store:
reducerPathis the key where the cache lives in the state.api.reducerstores cached results and request status.api.middlewareruns the fetching, caching, and cache expiry. Without it, the hooks do not work correctly.
The request lifecycle
The diagram shows what happens when a component calls the generated hook.
Reading the hook result
The hook returns an object with several fields:
| Field | Meaning |
|---|---|
| `data` | The latest result, if any |
| `isLoading` | True only during the first load, when no data exists yet |
| `isFetching` | True during any request, including refetches |
| `error` | The error, if the request failed |
A common mistake is to show a spinner using isFetching. The spinner then replaces valid data every time a refetch happens. Use isLoading for the first load and isFetching for a subtle refresh indicator.
Caching behavior
Results are cached by endpoint name and arguments. Calling useGetTodosQuery() in two components sends one request. Each hook call counts as a subscriber. When the last subscriber unmounts, RTK Query keeps the data for 60 seconds by default, then removes it. You can change this with keepUnusedDataFor.
Common errors
- Forgetting
api.middleware. Requests and cache cleanup misbehave. - Forgetting to add
api.reducerunderapi.reducerPath. - Importing hooks from
@reduxjs/toolkit/queryinstead of@reduxjs/toolkit/query/react. The non-React entry point does not generate hooks. - Copying
datainto a slice withuseEffect. This creates two sources of truth. Readdatafrom the hook directly.
Exercise
A component shows a full-page spinner whenever isFetching is true. Users report that the list disappears for a moment after they return to the tab. Why does this happen, and what is the fix?
Show answer
Returning to the tab can trigger a refetch, which sets isFetching to true even though cached data exists. The spinner then hides the list. Show the full-page spinner only when isLoading is true, and use isFetching for a small refresh indicator beside the existing data.