Lesson 10 / 25

createApi and Endpoints

Generated hooks for queries and mutations.

Define the API once

createApi from @reduxjs/toolkit/query/react takes a reducerPath, a baseQuery (often fetchBaseQuery({ baseUrl })) and an endpoints builder. Each builder.query reads data and each builder.mutation changes it. RTK Query generates React hooks named after the endpoints, such as useGetPostsQuery and useAddPostMutation, and stores results in the Redux store, deduplicating identical requests from several components. Add the API's reducer and middleware to the store.

Server state, cached for you

RTK Query is a data fetching and caching layer built into Redux Toolkit.

Three ideas: createApi endpoints, tags and invalidation, optimistic updates and polling.
Figure 4.1 — Components, the RTK Query cache and the server.

A posts API

api.ts and store wiring.

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

type Post = { id: number; title: string };

export const api = createApi({
  reducerPath: 'api',
  baseQuery: fetchBaseQuery({ baseUrl: '/api' }),
  endpoints: (builder) => ({
    getPosts: builder.query<Post[], void>({ query: () => 'posts' }),
    getPost: builder.query<Post, number>({ query: (id) => `posts/${id}` }),
    addPost: builder.mutation<Post, Omit<Post, 'id'>>({
      query: (body) => ({ url: 'posts', method: 'POST', body }),
    }),
  }),
});

export const { useGetPostsQuery, useGetPostQuery, useAddPostMutation } = api;

// store.ts
// reducer: { [api.reducerPath]: api.reducer, ... },
// middleware: (gDM) => gDM().concat(api.middleware)

One API slice per base URL

The docs recommend a single createApi per backend and splitting large APIs with injectEndpoints, so caching and tags stay in one place.

Quick check: What does RTK Query generate from a getPosts query endpoint?

  • A useGetPostsQuery React hook
  • A REST server
  • A database migration
  • A Zustand store
Answer

A useGetPostsQuery React hook — Hooks are named after the endpoints.