Suggest an editImprove this articleRefine the answer for “What is RTK Query?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)**RTK Query** is a library built into Redux Toolkit for working with server data: requests, caching, refetching, synchronization, and automatic loading states. **Key point:** RTK Query makes the requests, caches the responses, updates the UI, and manages status and errors itself - without `useEffect`, `dispatch`, or `thunk`.Shown above the full answer for quick recall.Answer (EN)Image## Short answer > **RTK Query** is a library built into Redux Toolkit for **working with server data**: > requests, caching, refetching, synchronization, and automatic loading states. That means: - you do not need to write `createAsyncThunk()`, - you do not need to store `loading`, `error`, `data` in the store, - you do not need a `useEffect` to load data - RTK Query **does all of that itself**. --- ## Main idea > RTK Query is like **React Query**, but built right into Redux. It automatically: - makes requests (`fetch`, `axios`, and so on), - caches responses, - tracks loading status, - updates components when data changes, - supports refetching, polling, and invalidation (refetching when dependencies change). --- ## Example - minimal working code ```javascript import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react' // 1. Create an API slice export const usersApi = createApi({ reducerPath: 'usersApi', // key in the store baseQuery: fetchBaseQuery({ baseUrl: '/api' }), endpoints: (builder) => ({ getUsers: builder.query({ query: () => '/users' }), getUserById: builder.query({ query: (id) => `/users/${id}` }), }) }) // 2. Export the hooks export const { useGetUsersQuery, useGetUserByIdQuery } = usersApi ``` --- ## Connecting to the store ```javascript import { configureStore } from '@reduxjs/toolkit' import { usersApi } from './usersApi' export const store = configureStore({ reducer: { [usersApi.reducerPath]: usersApi.reducer, }, middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(usersApi.middleware), }) ``` --- ## Using it in a React component ```javascript import { useGetUsersQuery } from './usersApi' function Users() { const { data, error, isLoading } = useGetUsersQuery() if (isLoading) return <p>Loading...</p> if (error) return <p>Error</p> return ( <ul> {data.map(user => ( <li key={user.id}>{user.name}</li> ))} </ul> ) } ``` That's it! No `useEffect`, `dispatch`, `createAsyncThunk`, `loading`, `error`. RTK Query makes the request itself, watches the cache, and updates the component. --- ## What RTK Query does under the hood RTK Query: 1. Automatically calls `fetch()` when the component mounts. 2. Caches the response in the Redux store. 3. If another component requests the same data, the **cache** is used instead of a new request. 4. You can "invalidate" the cache and refetch data manually. 5. Listens to WebSocket / polling for auto-updates (if needed). --- ## Two kinds of endpoints | Type | Used for | Example | |---|---|---| | `builder.query()` | GET requests (reading data) | `getUsers` | | `builder.mutation()` | POST / PUT / DELETE (changing data) | `addUser`, `updateUser` | ### Mutation example: ```javascript addUser: builder.mutation({ query: (newUser) => ({ url: '/users', method: 'POST', body: newUser }), invalidatesTags: ['Users'] // refetches getUsers }) ``` And in the component: ```javascript const [addUser, { isLoading }] = useAddUserMutation() addUser({ name: 'Tim' }) ``` --- ## Automatic states RTK Query automatically tracks: - `isLoading` - `isFetching` - `isSuccess` - `isError` - `error` - `data` Example: ```javascript const { data, isFetching, isError } = useGetUsersQuery() ``` --- ## Caching and refetching RTK Query stores cached data in the Redux store: ```javascript state.usersApi.queries.getUsers.data ``` You can configure: - the cache lifetime (`keepUnusedDataFor`) - automatic refetch on focus (`refetchOnFocus`) - refetch on reconnect (`refetchOnReconnect`) ```javascript baseQuery: fetchBaseQuery({ baseUrl: '/api' }), keepUnusedDataFor: 60, // sec refetchOnFocus: true, ``` --- ## Benefits of RTK Query | Problem with "manual" Redux | RTK Query's solution | |---|---| | You have to write `createAsyncThunk` | Makes the request automatically | | You have to store `loading/error/data` | It is all built in | | Duplicated requests across components | A single cache for everyone | | Complex refetching / polling | Out of the box | | No control over stale cache | Invalidation tags exist | | Separate code for requests and Redux | Everything in one API slice | --- ## RTK Query alongside Redux Toolkit RTK Query is part of RTK, not a separate library. You just import `createApi` and use it inside the same Redux store. It integrates with DevTools, middleware, and works on the same principles as Redux. --- ## Visually ```javascript [React component] | v useGetUsersQuery() | v [RTK Query] |-- Checks the cache |-- If missing -> makes a fetch |-- Stores the data in the store |-- Returns { data, isLoading, error } `-- Automatically updates the component on changes ``` --- ## Summary | Term | What it does | |---|---| | **RTK Query** | A tool for working with server data in Redux Toolkit | | **Main goal** | Automate requests, caching, loading, and errors | | **Main functions** | `createApi`, `fetchBaseQuery`, `builder.query`, `builder.mutation` | | **States** | `isLoading`, `isFetching`, `isSuccess`, `isError`, `data`, `error` | | **Key benefit** | Minimal code, maximum automation | --- **Bottom line:** > **RTK Query** is a powerful Redux Toolkit extension for managing **server data**. > It makes requests, caches responses, updates the UI, and manages status and errors - > all automatically, without `useEffect`, `dispatch`, or `thunk`.For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.