Skip to main content

What is RTK Query?

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

TypeUsed forExample
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" ReduxRTK Query's solution
You have to write createAsyncThunkMakes the request automatically
You have to store loading/error/dataIt is all built in
Duplicated requests across componentsA single cache for everyone
Complex refetching / pollingOut of the box
No control over stale cacheInvalidation tags exist
Separate code for requests and ReduxEverything 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

TermWhat it does
RTK QueryA tool for working with server data in Redux Toolkit
Main goalAutomate requests, caching, loading, and errors
Main functionscreateApi, fetchBaseQuery, builder.query, builder.mutation
StatesisLoading, isFetching, isSuccess, isError, data, error
Key benefitMinimal 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.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.