1/2 Series: RTK Query
RTK Query
An introduction to Redux Toolkit and RTK Query: createApi, connecting to the store, endpoints, auto-generated hooks, mutations, parameters and caching.
Introduction
RTK Query is Redux Toolkit’s tool for fetching data from an API and managing it in the application. To understand where it fits in, the post starts from the basics: what the difference is between Redux and Redux Toolkit, and how saga and slice relate to all of this. From there we move on to RTK Query itself: installation, defining endpoints, the hooks generated from them, mutations, parameters and caching.
Redux and Redux Toolkit
Redux is a state management library. It provides a predictable way to manage the application’s state.
Redux Toolkit is a library that simplifies writing Redux code. It provides ready-made tools that are used in almost every Redux application, and with them the same code is written in fewer lines:
configureStoresets up a Redux store with sensible defaults: it combines the reducers, adds the middleware, includes redux-thunk and turns on Redux DevTools.createSlicetakes an initial state, an object of reducer functions and a name, and automatically creates the actions and the reducer from them.createAsyncThunkhandles asynchronous actions: it takes a name for the action and a function that returns a Promise, and dispatches the actions for the start of the request, its success and its failure by itself.
saga and slice
Both concepts are related to Redux, but they are two different things.
redux-saga is a middleware library for Redux. It provides an organized and testable way to handle side effects, such as asynchronous API calls or working with the browser’s storage. Sagas are generator functions that listen for specific Redux actions and perform side effects in response to them.
A slice is one part of the application’s state together with its logic. It is created with Redux Toolkit’s createSlice, which returns both the actions and the reducer of that part. This saves a lot of boilerplate code and makes complex state structures easier to manage.
What is RTK Query
RTK Query is an add-on included in the Redux Toolkit package. It simplifies making API requests and managing the data they return, and it handles the patterns that recur in every application: loading and error states, caching and pagination.
Working with it starts with defining endpoints that describe the API: the address, the HTTP method and the data that is sent. From this definition RTK Query automatically creates everything needed to make the requests and manage the results in the Redux store, including ready-to-use hooks for components.
The main advantage is less boilerplate code and one consistent, predictable way to handle API requests. This makes the application easier to maintain and to extend over time.
Installation
RTK Query is part of the @reduxjs/toolkit package, and there is no separate package to install for it. In a React application you also need react-redux:
npm install @reduxjs/toolkit react-reduxOr:
yarn add @reduxjs/toolkit react-reduxThere is no need for axios. The requests are sent by fetchBaseQuery, which is a small wrapper around the browser’s fetch.
Defining the API
The API is defined with the createApi function. In a React application you import it from @reduxjs/toolkit/query/react, because only this entry point generates the hooks:
// api.js
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
export const api = createApi({
reducerPath: 'api',
baseQuery: fetchBaseQuery({ baseUrl: 'https://api.example.com' }),
endpoints: (builder) => ({
getUser: builder.query({
query: (id) => `/users/${id}`,
}),
}),
});
export const { useGetUserQuery } = api;In this example we defined an endpoint named getUser, which takes an id parameter and returns the data of a single user. The last line exports the hook that RTK Query generated for it.
Connecting to the store
For the hooks to work, you need to add two things the API provides to the Redux store: its reducer and its middleware. The middleware is what manages the cache, the invalidation of data and the polling.
// store.js
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),
});
// optional, but required for refetchOnFocus / refetchOnReconnect
setupListeners(store.dispatch);And the application is wrapped in react-redux’s Provider:
import { createRoot } from 'react-dom/client';
import { Provider } from 'react-redux';
import { store } from './store';
import App from './App';
createRoot(document.getElementById('root')).render(
<Provider store={store}>
<App />
</Provider>
);Using the hook in a component
Now data can be fetched from the API in any component:
import { useGetUserQuery } from './api';
function User({ id }) {
const { data, isLoading, isError } = useGetUserQuery(id);
if (isLoading) {
return <div>Loading...</div>;
}
if (isError) {
return <div>Failed to load the user</div>;
}
return (
<div>
<h1>{data.name}</h1>
<p>{data.bio}</p>
</div>
);
}The hook returns an object with the data, and with flags that indicate whether the data is currently loading or whether an error occurred.
Where the hook names come from
useGetUserQuery is not defined anywhere in the code we wrote, and it is not a reserved name either. createApi generates it automatically from the endpoint’s name and type:
- For a query:
use, followed by the endpoint name with a capital first letter, followed byQuery. The endpointgetUsergets the hookuseGetUserQuery. - For a mutation: the same structure with
Mutationat the end. The endpointcreateUsergets the hookuseCreateUserMutation.
The suffix is determined by the endpoint’s type, not by its name. There is no setting that changes the hook’s name: to get a different name, you change the endpoint’s name.
Endpoints: queries and mutations
An endpoint is the definition of one API request the application makes. Endpoints are defined in the endpoints property of createApi. It is a function that receives a builder object, and with it you define two kinds:
builder.queryfor requests that fetch data.builder.mutationfor requests that change data on the server: creating, updating or deleting.
Both kinds can be combined in the same call to createApi, and that is the usual case, because most applications both read from the API and write to it:
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
export const api = createApi({
reducerPath: 'api',
baseQuery: fetchBaseQuery({ baseUrl: 'https://api.example.com' }),
endpoints: (builder) => ({
getUsers: builder.query({
query: () => '/users',
}),
createUser: builder.mutation({
query: (user) => ({
url: '/users',
method: 'POST',
body: user,
}),
}),
}),
});
export const { useGetUsersQuery, useCreateUserMutation } = api;getUsers is a query that returns a list of users, and createUser is a mutation that creates a new user.
Every endpoint has a query function that describes the request. When an address is enough, the function returns a string, as in getUsers. When more than that is needed, it returns an object with url, method and body, as in createUser.
Using a mutation
A mutation hook returns an array. The first item is the function that triggers the request, and the second is an object with the request’s state:
import { useState } from 'react';
import { useCreateUserMutation } from './api';
function CreateUserForm() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [createUser, { isLoading, error, data }] = useCreateUserMutation();
const handleSubmit = (e) => {
e.preventDefault();
createUser({ name, email });
};
return (
<form onSubmit={handleSubmit}>
<input type="text" value={name} onChange={(e) => setName(e.target.value)} />
<input type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
<button type="submit" disabled={isLoading}>
{isLoading ? 'Creating user...' : 'Create user'}
</button>
{error && <div>Failed to create the user</div>}
{data && <div>User created: {data.name} ({data.email})</div>}
</form>
);
}When the form is submitted, createUser sends a POST request to /users with the user’s data. isLoading, error and data are used to show the request’s state.
Parameters
The parameters an endpoint accepts are defined in its query function. The function receives only one parameter, so when several values are needed you pass them in a single object:
endpoints: (builder) => ({
getUserById: builder.query({
query: (id) => `/users/${id}`,
}),
updateUserById: builder.mutation({
query: ({ id, name, email }) => ({
url: `/users/${id}`,
method: 'PATCH',
body: { name, email },
}),
}),
}),getUserById takes a single parameter, id, and builds the address from it. updateUserById takes an object with id, name and email, and builds the address and the request body from them.
To pass the parameters, you call the hook or the mutation function with that same value:
// query: the argument goes to the hook
const { data, isLoading, error } = useGetUserByIdQuery(userId);
// mutation: the argument goes to the trigger function
const [updateUserById, { isLoading: isUpdating }] = useUpdateUserByIdMutation();
updateUserById({ id: userId, name, email });Caching and identical requests
RTK Query caches the result of every query, by the endpoint and the parameter passed to it. Several behaviors that save unnecessary requests follow from this:
- Automatic caching: a repeated call to the same endpoint with the same parameter gets the data from the cache, without another request to the server.
- Identical requests in parallel: when several components call the same hook with the same parameter at the same time, only one request is sent, and all the components share the same data and the same loading state.
- Prefetching: the
usePrefetchhook lets you fetch data in the background before it is needed, for example when the mouse moves over a link. This way the next page loads faster.
import { api } from './api';
function NextUserButton({ nextId, onClick }) {
const prefetchUser = api.usePrefetch('getUser');
return (
<button onMouseEnter={() => prefetchUser(nextId)} onClick={onClick}>
Next user
</button>
);
}Requests to different endpoints simply run in parallel, each with its own hook:
import { useGetUserQuery, useGetProductQuery } from './api';
function App() {
const { data: userData, isFetching: isUserFetching } = useGetUserQuery('1');
const { data: productData, isFetching: isProductFetching } = useGetProductQuery('2');
if (isUserFetching || isProductFetching) {
return <div>Loading...</div>;
}
return (
<div>
<h1>{userData.name}</h1>
<p>{productData.description}</p>
</div>
);
}Here a loading indicator is shown until both requests finish. The example assumes that api.js also defines a getProduct endpoint, in the same way as getUser.
You can read about how long data stays in the cache and about refreshing data after an update in the follow-up post.
What to do when a mutation succeeds
Sometimes you want to run code after the mutation has succeeded, for example to go to another page or to update another part of the state. There are two ways to do this.
The first way is in the component itself. The function that triggers the mutation returns a Promise, and unwrap() makes it return the data or throw the error:
const [createPost] = useCreatePostMutation();
const handleSubmit = async (e) => {
e.preventDefault();
try {
const post = await createPost({ title, content }).unwrap();
// the request succeeded: post holds the server's response
} catch (err) {
// the request failed
}
};The second way is in the endpoint definition, with onQueryStarted. The function receives dispatch and queryFulfilled, which is a Promise that resolves when the request succeeds. In this example the new post is added to a slice of our own:
import { createSlice } from '@reduxjs/toolkit';
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
const postsSlice = createSlice({
name: 'posts',
initialState: [],
reducers: {
addPost: (state, action) => {
state.push(action.payload);
},
},
});
export const { addPost } = postsSlice.actions;
export const postsReducer = postsSlice.reducer;
export const api = createApi({
reducerPath: 'api',
baseQuery: fetchBaseQuery({ baseUrl: 'https://api.example.com' }),
endpoints: (builder) => ({
createPost: builder.mutation({
query: (post) => ({
url: '/posts',
method: 'POST',
body: post,
}),
async onQueryStarted(post, { dispatch, queryFulfilled }) {
try {
const { data } = await queryFulfilled;
dispatch(addPost(data));
} catch (err) {
// the request failed
}
},
}),
}),
});
export const { useCreatePostMutation } = api;After the request succeeds, the new post is stored in the Redux store and can be used in other parts of the application.
In most cases there is no need to copy data from the server into a separate slice. RTK Query’s cache already holds it, and tags take care of refreshing it after a mutation. You can read about that in the follow-up post as well.
Summary
- Redux Toolkit simplifies writing Redux code, and RTK Query is the part of it that handles API requests.
- You define the API once with
createApi, connect its reducer and middleware to the store, and get a ready-made hook for every endpoint. - Queries fetch data and mutations change it. The hook’s name is derived from the endpoint’s name and type.
- Results are cached by endpoint and parameter, and identical requests are merged into one request.
Further reading: the official RTK Query documentation.