advanced
Redux Toolkit Query
Handle server-state fetching, caching, invalidation tags, generated hooks, and request lifecycle in Redux apps.
RTK Query adds a data-fetching and caching layer inside Redux: endpoints define queries and mutations, generated hooks manage loading/error/data, and cache tags drive invalidation.
const api = createApi({
reducerPath: 'api',
baseQuery: fetchBaseQuery({ baseUrl: '/api' }),
tagTypes: ['Post'],
endpoints: (build) => ({
getPosts: build.query({
query: () => 'posts',
providesTags: ['Post'],
}),
addPost: build.mutation({
query: (body) => ({ url: 'posts', method: 'POST', body }),
invalidatesTags: ['Post'],
}),
}),
});
// const { data } = api.useGetPostsQuery();
It deduplicates in-flight requests, caches by serialized query args, and supports optimistic updates via `onQueryStarted`. Not for local UI drafts — pair with slice state for form interaction.
The trade-off is integrated server cache in Redux versus bundle size and learning curve separate from client slices.
On interviews: how tags connect writes to cached reads; RTK Query vs TanStack Query in greenfield apps.
Common pitfalls: storing all app state in RTK Query, missing tag granularity causing over-invalidation, and mutations without rollback plan.
Checklist:
- Endpoints colocated in createApi slice.
- providesTags / invalidatesTags graph.
- Generated hooks in components.
- Client UI state stays outside RTK Query cache.