RTK Query is the data-fetching and caching layer of Redux Toolkit. It generates hooks for API calls and manages loading states, caching, deduplication and cache invalidation. 1. Define an API slice import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'; export const api = createApi({ reducerPath: 'api', baseQuery: fetchBaseQuery({ baseUrl: '/api', prepareHeaders: (headers, { getState }) => { const token = (getState() as RootState).auth.token; if (token) headers.set('Authorization', `Bearer ${token}`); return headers; }, }), tagTypes: ['Product'], endpoints: builder => ({ getProducts: builder.query<Product[], { page: number }>({ query: ({ page }) => `products?page=${page}`, providesTags: result => result ? [...result.map(p => ({ type: 'Product' as const, id: p.id })), { type: 'Product', id: 'LIST' }] : [{ type: 'Product', id: 'LIST' }], }), updateProduct: builder.mutation<Product, Partial<Product> & { id: number }>({ query: ({ id, ...body }) => ({ url: `products/${id}`, method: 'PUT', body }), invalidatesTags: (_r, _e, { id }) => [{ type: 'Product', id }, { type: 'Product', id: 'LIST' }], }), }), }); export const { useGetProductsQuery, useUpdateProductMutation } = api; 2. Add it to the store export const store = configureStore({ reducer: { [api.reducerPath]: api.reducer, auth: authReducer }, middleware: getDefault => getDefault().concat(api.middleware), }); setupListeners(store.dispatch); // enables refetchOnFocus / refetchOnReconnect 3. Use the generated hooks in components function ProductList() { const [page, setPage] = useState(1); const { data, isLoading, isFetching, error } = useGetProductsQuery({ page }); const [updateProduct, { isLoading: saving }] = useUpdateProductMutation(); if (isLoading) return <p>Loading…</p>; if (error) return <p>Could not load products.</p>; return ( <ul> {data!.map(p => ( <li key={p.id}> {p.name} <button disabled={saving} onClick={() => updateProduct({ id: p.id, price: p.price * 0.9 })}>Discount</button> </li> ))} </ul> ); } Features worth mentioning - Automatic caching and request deduplication: several components using the same query share one request. - Tags (providesTags and invalidatesTags) refetch affected queries after mutations. - Optimistic updates with onQueryStarted and api.util.updateQueryData, rolled back on failure. - Polling (pollingInterval), conditional fetching (skip), and keepUnusedDataFor for cache lifetime. - Token refresh: wrap baseQuery to retry once after refreshing on 401. - Code generation from OpenAPI with @rtk-query/codegen-openapi. RTK Query is a good choice when the app already uses Redux; otherwise TanStack Query offers similar capabilities without Redux.
Ravindra Wadile · · 0 likes