Server State in React with RTK Query: Caching, Invalidation and Optimistic Updates

By Muhammad Osama Khan, Software Engineer. React, Nov 3, 2026, 4 min read.

Stop hand-writing loading flags and refetch logic. Define endpoints once, tag the data and let RTK Query keep the cache correct.

Data that comes from an API is a different thing from UI state: it can be stale, it is shared by many components, and it needs loading and error handling. RTK Query, which ships inside Redux Toolkit, treats it that way. You describe your endpoints once and get hooks, caching, de-duplicated requests and refetching.

Define the API once

Tags are the key idea. A query says which tags it provides; a mutation says which tags it invalidates. When a mutation succeeds, every query that provided an invalidated tag refetches by itself.

src/services/api.js

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

export const api = createApi({
  reducerPath: 'api',
  baseQuery: fetchBaseQuery({
    baseUrl: '/api',
    credentials: 'include',
    prepareHeaders: (headers, { getState }) => {
      const token = getState().auth.accessToken;
      if (token) headers.set('Authorization', 'Bearer ' + token);
      return headers;
    }
  }),
  tagTypes: ['Task'],
  endpoints: (build) => ({
    getTasks: build.query({
      query: () => '/tasks',
      providesTags: (result = []) => [
        ...result.map(({ _id }) => ({ type: 'Task', id: _id })),
        { type: 'Task', id: 'LIST' }
      ]
    }),
    addTask: build.mutation({
      query: (body) => ({ url: '/tasks', method: 'POST', body }),
      invalidatesTags: [{ type: 'Task', id: 'LIST' }]
    })
  })
});

export const { useGetTasksQuery, useAddTaskMutation } = api;

Register it in the store

src/store.js

import { configureStore } from '@reduxjs/toolkit';
import { api } from './services/api';
import authReducer from './features/authSlice';

export const store = configureStore({
  reducer: {
    auth: authReducer,
    [api.reducerPath]: api.reducer
  },
  middleware: (getDefault) => getDefault().concat(api.middleware)
});

Use the hooks

No useEffect, no useState for loading and error. Two components that call the same query share one request and one cache entry.

src/components/TaskList.jsx

import { useGetTasksQuery, useAddTaskMutation } from '../services/api';

export default function TaskList() {
  const { data: tasks = [], isLoading, isError, refetch } = useGetTasksQuery();
  const [addTask, { isLoading: isAdding }] = useAddTaskMutation();

  if (isLoading) return <p>Loading tasks…</p>;
  if (isError) return <button onClick={refetch}>Could not load. Try again</button>;

  return (
    <>
      <button disabled={isAdding} onClick={() => addTask({ title: 'New task' })}>
        Add task
      </button>
      <ul>
        {tasks.map((t) => <li key={t._id}>{t.title}</li>)}
      </ul>
    </>
  );
}

After addTask succeeds, the LIST tag is invalidated and getTasks refetches. The list updates without you wiring anything.

Optimistic updates with rollback

For actions that almost always succeed (ticking a checkbox), waiting for the server makes the UI feel slow. Update the cache immediately, and undo it if the request fails.

src/services/api.js

toggleTask: build.mutation({
  query: ({ id, done }) => ({ url: '/tasks/' + id, method: 'PATCH', body: { done } }),

  async onQueryStarted({ id, done }, { dispatch, queryFulfilled }) {
    // 1. change the cached list straight away
    const patch = dispatch(
      api.util.updateQueryData('getTasks', undefined, (draft) => {
        const task = draft.find((t) => t._id === id);
        if (task) task.done = done;
      })
    );
    // 2. if the server rejects it, put the old value back
    try {
      await queryFulfilled;
    } catch {
      patch.undo();
    }
  }
})

Settings worth knowing

  • keepUnusedDataFor controls how long cached data stays after the last component stops using it (60 seconds by default).
  • refetchOnFocus and refetchOnReconnect (enabled with setupListeners(store.dispatch)) refresh data when the user returns to the tab or the network comes back.
  • skip stops a query from running until you have what it needs, for example a selected id.
  • selectFromResult lets a component subscribe to only the slice it renders, which avoids needless re-renders in long lists.

Keep Redux slices for real client state (the signed-in user, UI filters, a draft) and leave everything that originates on the server to RTK Query.

Frequently asked questions

What is RTK Query used for?

Fetching and caching server data in a React app. It is included in Redux Toolkit: you describe your endpoints once and get hooks with loading and error state, de-duplicated requests, caching and automatic refetching.

What is the difference between providesTags and invalidatesTags?

A query uses providesTags to say which pieces of data its result contains. A mutation uses invalidatesTags to say which pieces it changed. When the mutation succeeds, every query that provides an invalidated tag refetches by itself.

How long does RTK Query keep cached data?

By default, 60 seconds after the last component that used a query unmounts. Change it with keepUnusedDataFor, globally or per endpoint.

How do optimistic updates work in RTK Query?

In onQueryStarted, update the cached data straight away with updateQueryData, then await the request. If it fails, call undo() on the returned patch result to restore the previous value.

Keep reading

All articles · Work with me

MO
Muhammad Osama Khan