Cached queries
Define read endpoints whose responses should be cached and reused across components.
Redux Toolkit · Function
createApi defines RTK Query endpoints and their request behavior, then generates an API slice for Redux data fetching and caching. The React-specific entry point additionally generates hooks for those endpoints.
Call createApi with a baseQuery or custom request logic and an endpoints builder. It returns an API slice containing Redux reducer and middleware integration, endpoint thunks and selectors, and—when imported from the React entry point—generated hooks.
createApi(options)| Name | Type | Description |
|---|---|---|
options | CreateApiOptions | Configuration object defining the API slice, including baseQuery or endpoint request logic, reducerPath, and endpoint builders. |
An API service slice containing a reducer, middleware, endpoint thunks, selectors, and, for the React entry point, generated hooks.
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
export const postsApi = createApi({
reducerPath: 'postsApi',
baseQuery: fetchBaseQuery({ baseUrl: '/api' }),
endpoints: (build) => ({
getPosts: build.query<Post[], void>({
query: () => 'posts',
}),
}),
})
export const { useGetPostsQuery } = postsApiThis creates an API slice with a base URL and a cached query endpoint, then exposes the generated React hook.
Define read endpoints whose responses should be cached and reused across components.
Describe server writes and coordinate invalidation or refetching of related cached queries.
Expose endpoint-specific React hooks from a UI-integrated API service.
Use custom asynchronous logic when a request cannot be expressed through the configured baseQuery.
createApi is RTK Query's central API-definition function. It describes endpoints and request behavior, then generates an API slice with Redux logic for fetching and caching; the React entry point also generates hooks.
Follow-up: How is the generated slice integrated into Redux? Add its reducer at the configured reducerPath and include its middleware in configureStore.
The baseQuery establishes the default request mechanism and can be used by endpoints that provide a query value. An endpoint can instead provide queryFn when it needs custom asynchronous logic.
Follow-up: What endpoint kinds are available? Query endpoints cache fetched data, infiniteQuery endpoints support infinite data, and mutation endpoints send server updates and can invalidate queries.
The returned API object includes endpoint-specific Redux thunks and selectors. With the React-specific import, it also includes generated hooks for those endpoints.
Follow-up: What must be configured in the store? Add the API reducer using reducerPath and the API middleware so cache lifetimes, subscriptions, invalidation, and polling operate.
fetchBaseQuerybuild.querybuild.infiniteQuerybuild.mutationreducerPathconfigureStore