Request Behavior: When Queries Run and Refetch
This page explains when RTK Query calls your query function. It answers three questions:
- Will this call start a request, or use the cache?
- What makes cached data refetch?
- What happens when a request fails?
A "request" here means one call to the endpoint's query or queryFn. It doesn't have to be an HTTP request.
How long data stays in the store after it is fetched, and what removes it, is covered in Cache Behavior. That page also explains cache entries and subscriptions, which this page relies on. In short:
- A cache entry holds the result of one endpoint called with one argument.
- A subscription is a claim that something is using the entry. Each mounted
useQueryhook holds one. So does eachinitiate()call, unless it passessubscribe: false. - A running request is a request for the entry that has started and not finished yet.
Cached data has no "stale" state. Data stays valid until something refetches it or removes it. If you know TanStack Query, the default behaves like staleTime: Infinity, with tag invalidation deciding when data refetches. See Coming from TanStack Query.
Will this call start a request?
A useQuery hook, initiate(), prefetch, and a lazy query trigger all go through the same check. RTK Query applies these rules in order and stops at the first one that matches:
- The argument is
skipToken, or the hook hasskip: true: no request. - A request for this entry is already running: the call joins it and gets its result. This is true even for
refetch()andforceRefetch: true. RTK Query never runs two requests for the same entry at the same time. - The call is forced (see the table below): start a request.
- The endpoint's
forceRefetchcallback returnstrue: start a request. - The entry has succeeded at least once: use the cache.
- Otherwise, start a request.
prefetch with ifOlderThan checks the data's age first. If the data is younger than that, it returns without running any of these rules, so the endpoint's forceRefetch callback is not called.
A new subscriber to an entry that already has data does not refetch it. Mounting a second component with the same hook and argument reuses the data.
Options that force a request
| Option | Where it is set | Values | Default |
|---|---|---|---|
refetchOnMountOrArgChange | createApi, useQuery hook options | boolean or seconds | false |
forceRefetch | initiate() options | boolean or seconds | not set |
preferCacheValue | lazy query trigger, second argument | boolean | false |
force / ifOlderThan | prefetch options | boolean / seconds | not set |
forceRefetch callback | endpoint definition | function returning boolean | not set |
How the values work (preferCacheValue is the exception: it is reversed, see below):
truealways starts a request.- A number
nstarts a request if the data is at leastnseconds old, or if there is no data yet. 0behaves liketrueforrefetchOnMountOrArgChangeandforceRefetch. Forprefetch,ifOlderThan: 0does not force a request. It behaves like passing no options.falseuses the normal rules.
What wins when it is set in more than one place:
- The
useQueryhook'srefetchOnMountOrArgChangeis passed toinitiate()asforceRefetch. An explicitforceRefetch(or hook value) overrides thecreateApivalue. - The
createApivalue ofrefetchOnMountOrArgChangeonly applies to calls that subscribe.initiate(arg, { subscribe: false })andprefetchignore it. - A lazy query trigger always fetches, unless you pass
preferCacheValue: true. Then it uses the normal rules. - The endpoint's
forceRefetchcallback runs only when the call isn't already forced. It cannot stop a forced request.
refetchOnMountOrArgChange
Use refetchOnMountOrArgChange when a component should not trust cached data that might be old. It is checked each time a hook mounts or its argument changes. It isn't checked on re-renders.
- TypeScript
- JavaScript
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
import type { Post } from './types'
export const api = createApi({
baseQuery: fetchBaseQuery({ baseUrl: '/' }),
refetchOnMountOrArgChange: 30,
endpoints: (build) => ({
getPosts: build.query<Post[], void>({
query: () => `posts`,
}),
}),
})
export const { useGetPostsQuery } = api
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
export const api = createApi({
baseQuery: fetchBaseQuery({ baseUrl: '/' }),
refetchOnMountOrArgChange: 30,
endpoints: (build) => ({ getPosts: build.query({ query: () => `posts` }) }),
})
export const { useGetPostsQuery } = api
import { useGetPostsQuery } from './api'
const Component = () => {
const { data } = useGetPostsQuery(
undefined,
// overrides the createApi value for this hook only
{ refetchOnMountOrArgChange: true },
)
return <div>...</div>
}
What triggers a refetch?
Several events refetch an entry that already has data. The automatic triggers (tag invalidation, focus, reconnect, and polling) only refetch entries that have subscribers. refetch() is an explicit call and always runs. Some of them remove unused entries instead. See Removing data earlier.
| Trigger | Where it is set | Values | Default |
|---|---|---|---|
| Tag invalidation | endpoint providesTags / invalidatesTags, api.util.invalidateTags | tags | none |
refetchOnFocus | createApi, useQuery hook options, initiate() subscriptionOptions | boolean or seconds | false |
refetchOnReconnect | same as refetchOnFocus | boolean or seconds | false |
pollingInterval | useQuery hook options, initiate() subscriptionOptions | milliseconds, or a function | 0 (off) |
refetch() | hook result, initiate() result | — | — |
refetch() and forceRefetch: true
refetch() is returned by the query hooks and by initiate(). It forces a request for that entry. If a request is already running, refetch() joins it instead of starting a new one.
refetch() is the same as dispatching initiate(arg, { subscribe: false, forceRefetch: true }):
import { useDispatch } from 'react-redux'
import { api, useGetPostsQuery } from './api'
const Component = () => {
const dispatch = useDispatch()
const { data, refetch } = useGetPostsQuery()
function handleRefetchOne() {
refetch()
}
function handleRefetchTwo() {
// same effect as `refetch()`
dispatch(
api.endpoints.getPosts.initiate(undefined, {
subscribe: false,
forceRefetch: true,
}),
)
}
return (
<div>
<button onClick={handleRefetchOne}>Force re-fetch 1</button>
<button onClick={handleRefetchTwo}>Force re-fetch 2</button>
</div>
)
}
Focus and reconnect
refetchOnFocus refetches subscribed queries when the window regains focus. refetchOnReconnect refetches them when the network connection comes back. Both work the same way.
Both need setupListeners. Without it, RTK Query never sees focus or network events.
- TypeScript
- JavaScript
import { configureStore } from '@reduxjs/toolkit'
import { setupListeners } from '@reduxjs/toolkit/query'
import { api } from './services/api'
export const store = configureStore({
reducer: {
[api.reducerPath]: api.reducer,
},
middleware: (gDM) => gDM().concat(api.middleware),
})
setupListeners(store.dispatch)
import { configureStore } from '@reduxjs/toolkit'
import { setupListeners } from '@reduxjs/toolkit/query'
import { api } from './services/api'
export const store = configureStore({
reducer: { [api.reducerPath]: api.reducer },
middleware: (gDM) => gDM().concat(api.middleware),
})
setupListeners(store.dispatch)
The values:
false(the default) never refetches.truealways refetches.- A number
nrefetches only if the data is at leastnseconds old, or if there is no data yet.0behaves liketrue. This lets you refetch on focus without starting a request every time the user switches tabs:
// Refetch on focus only if the data is at least 5 minutes old
const { data } = useGetPostsQuery(undefined, { refetchOnFocus: 300 })
Each subscriber has its own value. A subscriber that doesn't set one uses the createApi value. The entry refetches if any subscriber's value allows it, so the most eager value wins. With one subscriber at 60 and another at 10, data that is 20 seconds old is refetched. One subscriber passing false does not stop another subscriber from refetching.
Both options can be set on createApi, on the useQuery, useQuerySubscription, useLazyQuery, and useLazyQuerySubscription hooks, and in initiate() subscriptionOptions. A hook with skip: true holds no subscription, so its value isn't used until skip is false.
Polling
Polling refetches an entry on a timer. These rules matter when polling is combined with other options:
- With several subscribers, the entry polls at the shortest interval.
- The interval counts from when the previous response arrives, not from when it was sent.
- Polling needs a subscription.
initiate(arg, { subscribe: false })never polls. - Turning polling on with
updateSubscriptionOptionsdoes not fetch right away. The first poll runs after one interval. - With
skipPollingIfUnfocused, polls are skipped only if every polling subscriber sets it. Skipped polls are not made up when the window gets focus again. UserefetchOnFocusfor that. The focus state comes fromsetupListeners.
Tag invalidation
Queries provide tags with providesTags. Mutations invalidate tags with invalidatesTags. api.util.invalidateTags invalidates tags directly. Automated Re-fetching explains how to design tags. Matching follows two rules:
- A tag with only a type, like
'Post'or{ type: 'Post' }, invalidates every provided tag of that type, with or without an ID. - A tag with a type and an ID, like
{ type: 'Post', id: 1 }, invalidates only provided tags with that exact type and ID.
Tag Invalidation Behavior has a table of examples.
A mutation invalidates its tags when it finishes. That includes mutations that fail with an error from the base query. The invalidatesTags callback receives the error, so you can return no tags for failures.
When an entry is invalidated:
- If it has subscribers, it refetches.
- If it has no subscribers, it is removed right away. It isn't refetched.
- If a request for it is running, RTK Query waits for that request to finish, then refetches or removes the entry.
invalidationBehavior controls timing:
'delayed'(the default) waits until no query or mutation in this API is running. Then it applies all queued invalidations at once. This avoids refetching data that a running request is about to change again.'immediately'applies each invalidation right away. An entry whose request was running at the time is refetched after that request finishes. This also covers a first fetch that was running when the invalidation happened, and whose result provides a matching tag.
What happens when a request fails
A failed request sets the entry's status to 'rejected' and stores the error. It keeps any data from an earlier success.
That earlier success matters for the next caller:
- If the entry never succeeded, each new subscriber or
initiate()call starts a new request. - If the entry succeeded before, new subscribers use the cached entry and don't refetch. Call
refetch()or use one of the refetch triggers to try again.
After a failure, polling continues at the same interval. A query can provide tags for an error result, so a later mutation can invalidate it. See Providing errors to the cache.
RTK Query does not retry failed requests by default. Wrap the base query with retry to add retries:
| Option | Where it is set | Default |
|---|---|---|
maxRetries | retry() options, endpoint extraOptions | 5 (six attempts in total) |
retryCondition | retry() options, endpoint extraOptions | retry until maxRetries |
backoff | retry() options, endpoint extraOptions | exponential backoff |
- Endpoint
extraOptionsoverride theretry()options. - If an endpoint sets only
maxRetriesandretry()has aretryCondition, both apply: a retry happens only if the condition passes and the limit isn't reached. retry.fail(error)inside a base query stops retrying at once.- The entry stays
pendingthrough all attempts. Other callers join the same request. - Endpoints that use
queryFndon't go through the base query, soretrydoesn't apply to them.
Coming from TanStack Query
| TanStack Query | RTK Query |
|---|---|
staleTime | No direct equivalent. The default is like staleTime: Infinity. Use tags, refetchOnMountOrArgChange with seconds, or refetchOnFocus with seconds. |
gcTime (milliseconds) | keepUnusedDataFor (seconds) |
invalidateQueries marks unused queries stale | Invalidation removes unused entries and refetches entries with subscribers. |
refetch() can cancel a running request | refetch() joins a running request. |
retry: 3 on by default | No retries unless you wrap the base query with retry. |