RTK Query: Declarative Data Fetching
What You'll Learn
You'll learn how RTK Query's createApi automatically handles caching, refetching, and request deduplication, so you never write the same fetch logic twice.
The Problem RTK Query Solves
Until now, fetching data in Redux meant writing async thunks, managing loading states, handling errors, and manually deciding when to refetch. Every endpoint required this boilerplate. RTK Query eliminates this by treating data fetching as configuration, not code.
Think of it like ordering from a restaurant: instead of going to the kitchen yourself (writing fetch logic), you tell a waiter what you want (define an endpoint), and they handle everything—knowing when to bring fresh food, when leftovers are fine, and never taking duplicate orders.
How createApi Works
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
const api = createApi({
reducerPath: 'api',
baseQuery: fetchBaseQuery({ baseUrl: '/api' }),
endpoints: (builder) => ({
getUser: builder.query({
query: (userId) => `/users/${userId}`,
}),
updateUser: builder.mutation({
query: ({ id, ...patch }) => ({
url: `/users/${id}`,
method: 'PATCH',
body: patch,
}),
}),
}),
});
export const { useGetUserQuery, useUpdateUserMutation } = api;
You declare what data you need, not how to fetch it. RTK Query generates hooks that automatically:
- Cache responses by endpoint + arguments
- Deduplicate requests (two components requesting the same user? One network call)
- Refetch when data goes stale or on window focus
- Manage loading/error states without extra reducers
function UserProfile({ userId }) {
const { data, error, isLoading } = useGetUserQuery(userId);
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error!</div>;
return <div>{data.name}</div>;
}
Key Takeaway: RTK Query's createApi transforms data fetching from imperative async logic into declarative endpoint definitions, with automatic caching, deduplication, and refetching built-in—eliminating most boilerplate for server state management.