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 included in the @reduxjs/toolkit package, so you don't need to install anything else.
What RTK Query replaces
With createAsyncThunk you write the same things for every endpoint. You write a thunk, a slice with pending, fulfilled and rejected cases, a status field, an error field, and an effect that dispatches the thunk. You also decide when to refetch and how to avoid duplicate requests.
RTK Query is a data fetching and caching layer built on top of those pieces. You describe your endpoints once. It generates hooks that fetch the data, track loading and error state, cache results, and share one request among components that ask for the same data.
Use it for server state, meaning data that lives on a server and that your UI only borrows. Keep client state, such as a selected tab or a draft form, in ordinary slices.
Defining an API slice
An API slice is created with createApi. It needs four things:
reducerPathis the key under which the cache is stored in the Redux state.baseQueryis the function that performs requests.fetchBaseQueryis a small wrapper aroundfetch.tagTypeslists the labels used for cache invalidation (covered below).endpointsis where you define each query and mutation.
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
export const api = createApi({
reducerPath: 'api',
baseQuery: fetchBaseQuery({ baseUrl: '/api' }),
tagTypes: ['Todo'],
endpoints: (builder) => ({
getTodos: builder.query({
query: () => 'todos',
providesTags: (result = []) => [
...result.map(({ id }) => ({ type: 'Todo', id })),
{ type: 'Todo', id: 'LIST' },
],
}),
getTodo: builder.query({
query: (id) => `todos/${id}`,
providesTags: (result, error, id) => [{ type: 'Todo', id }],
}),
addTodo: builder.mutation({
query: (body) => ({ url: 'todos', method: 'POST', body }),
invalidatesTags: [{ type: 'Todo', id: 'LIST' }],
}),
updateTodo: builder.mutation({
query: ({ id, ...patch }) => ({
url: `todos/${id}`,
method: 'PATCH',
body: patch,
}),
invalidatesTags: (result, error, { id }) => [{ type: 'Todo', id }],
}),
}),
})
export const {
useGetTodosQuery,
useGetTodoQuery,
useAddTodoMutation,
useUpdateTodoMutation,
} = apiImport from @reduxjs/toolkit/query/react, not @reduxjs/toolkit/query. Only the /react entry point generates hooks.
The hook names come from the endpoint names. getTodos becomes useGetTodosQuery, and addTodo becomes useAddTodoMutation.
A query endpoint reads data. A mutation endpoint changes data on the server. The query function returns either a URL string or an object with url, method and body.
Adding the API slice to the store
The API slice needs both its reducer and its middleware. The middleware handles cache lifetimes, polling and invalidation.
import { configureStore } from '@reduxjs/toolkit'
import { setupListeners } from '@reduxjs/toolkit/query'
import { api } from './api'
export const store = configureStore({
reducer: {
[api.reducerPath]: api.reducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(api.middleware),
})
setupListeners(store.dispatch)setupListeners is optional. It enables the refetchOnFocus and refetchOnReconnect options, which are off until you turn them on.
The store is provided to React with Provider, exactly as in the earlier chapter. If you don't use Redux for anything else, ApiProvider is a lighter alternative, but most apps already have a store.
Using the generated hooks
import { useGetTodosQuery, useAddTodoMutation } from './api'
export function TodoList() {
const { data: todos = [], isLoading, isFetching, error, refetch } =
useGetTodosQuery()
const [addTodo, { isLoading: isAdding }] = useAddTodoMutation()
async function handleAdd() {
try {
await addTodo({ title: 'New todo', completed: false }).unwrap()
} catch (err) {
console.error('Could not add todo', err)
}
}
if (isLoading) return <p>Loading...</p>
if (error) return <p>Something went wrong.</p>
return (
<div>
<button onClick={handleAdd} disabled={isAdding}>Add</button>
<button onClick={refetch}>Refresh</button>
{isFetching && <span>Updating...</span>}
<ul>
{todos.map((t) => (
<li key={t.id}>{t.title}</li>
))}
</ul>
</div>
)
}Two status flags are easy to confuse:
| Flag | True when |
|---|---|
| `isLoading` | The query is fetching and has no data yet. This is the first load only. |
| `isFetching` | Any request is in flight, including a background refetch with data already showing. |
Showing a full-page spinner on isFetching makes the UI flash on every refetch. Use isLoading for the spinner and isFetching for a subtle indicator.
A query hook returns an object. A mutation hook returns a tuple: a trigger function and a result object. The trigger returns a promise. That promise resolves with an object that has either data or error, and it never rejects. Call .unwrap() if you want it to throw on failure, as handleAdd does above.
How caching works
Each query result is stored under a cache key made from the endpoint name and the serialized argument. useGetTodoQuery(1) and useGetTodoQuery(2) are two separate cache entries. Calling useGetTodoQuery(1) in ten components creates one entry and one request.
The cache entry keeps a count of subscribers, which are the mounted components using it. When the last subscriber unmounts, the entry is removed after keepUnusedDataFor seconds. The default is 60.
This is why navigating back to a page often shows its data instantly. The entry is still in the cache, and a new subscriber attaches to it.
Invalidating the cache with tags
After a mutation, cached data may be stale. Tags tell RTK Query which cached queries to refetch.
providesTagson a query says which tags that cached result represents.invalidatesTagson a mutation says which tags are now stale.
When a mutation succeeds, every active query that provides a matching tag is refetched. Queries that no subscriber is using are dropped from the cache instead.
In the example above, addTodo invalidates { type: 'Todo', id: 'LIST' }, so getTodos refetches and the new item appears. updateTodo invalidates one item by id. That refetches getTodos, because its result provides a tag for each item, and it refetches that item's getTodo entry. The 'LIST' id is a convention, not a special value. It stands for "the collection as a whole", which lets you refresh the list when items are added or removed.
Options you will use
Pass options as the second argument to a query hook.
const { data } = useGetTodoQuery(todoId, {
skip: !todoId,
pollingInterval: 30000,
refetchOnMountOrArgChange: true,
refetchOnFocus: true,
})skipprevents the request. Use it when an argument isn't available yet.pollingIntervalrefetches every N milliseconds while the component is mounted.refetchOnMountOrArgChangeforces a refetch when the component mounts instead of using cached data. You can also pass a number of seconds so that only older data is refetched.refetchOnFocusandrefetchOnReconnectrefetch when the window regains focus or the network returns. They needsetupListeners.
Set keepUnusedDataFor per endpoint or in createApi to change how long unused data is kept.
A callout on one common pattern:
Common errors
- Forgetting the middleware. The hooks seem to work, but caching, polling and invalidation don't. Redux Toolkit logs a warning in development. Add
api.middlewareto the store. - Wrong
reducerPath. The key you use inreducermust matchapi.reducerPath. Using[api.reducerPath]as the key avoids a mismatch. - Importing
createApifrom the wrong path. The core import has no hooks, souseGetTodosQueryisundefined. - Missing
tagTypes. Tags that aren't declared cause a type error in TypeScript and prevent invalidation from being set up cleanly. - Mutating
data. Query results are frozen in development. Copy the array before sorting it, with[...data].sort(...). - Unstable arguments. Passing a new object each render is fine, because arguments are serialized into the cache key. Passing non-serializable values such as class instances or functions is not.
- Treating the cache as a store you write to. Don't copy
datainto a slice withuseEffect. Read it from the hook, or from the generated selectors, when you need it elsewhere.
Choosing between RTK Query and createAsyncThunk
Pick RTK Query when you fetch data from an API, want caching and deduplication, and want loading state without hand-written reducers. Pick createAsyncThunk when the work is not a simple fetch-and-cache cycle, such as a multi-step workflow, or when you need the result in a slice for other reasons. The two can live side by side in one store.
Exercise
A user adds a todo with useAddTodoMutation, but the list from useGetTodosQuery doesn't update until the page is reloaded. The getTodos endpoint has providesTags: ['Todo'] and addTodo has no invalidatesTags field. What is missing, and what should you add?
Show answer
The mutation never tells RTK Query that the cached list is stale. Add invalidatesTags: ['Todo'] to addTodo, with 'Todo' declared in tagTypes. When the mutation succeeds, the active getTodos query has a matching tag, so it refetches and the new item appears.
Exercise
A component shows a spinner whenever isFetching is true, and users complain that the list flashes every time they return to the browser tab. Which flag should the spinner use, and which option is probably causing the extra requests?
Show answer
Use isLoading, which is true only while there is no data yet. Show a small indicator for isFetching instead. The extra requests most likely come from refetchOnFocus: true, together with setupListeners in the store setup, which refetches whenever the window regains focus.