Enable focus and reconnect refetching
Standard RTK Query store configuration
Redux Toolkit · Function
Enables RTK Query to react to browser focus and network reconnect events. Pass the store's dispatch to use the recommended defaults, or provide a custom handler for finer control.
setupListeners connects RTK Query to browser focus and network-status events by registering handlers that dispatch its internal lifecycle actions. Calling it with the store's dispatch enables the standard refetch behaviors; an optional callback can replace the default event wiring.
setupListeners(dispatch, customHandler?)| Name | Type | Description |
|---|---|---|
dispatch | ThunkDispatch<any, any, any> | The Redux store dispatch function used to dispatch RTK Query lifecycle actions. |
customHandler | (dispatch, actions) => () => void | Optional function that installs custom listeners and returns an unsubscribe function. |
An unsubscribe function that removes the registered listeners.
import { configureStore } from '@reduxjs/toolkit'
import { setupListeners } from '@reduxjs/toolkit/query'
import { pokemonApi } from './services/pokemon'
const store = configureStore({
reducer: { [pokemonApi.reducerPath]: pokemonApi.reducer },
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(pokemonApi.middleware),
})
setupListeners(store.dispatch)Create the store with the API reducer and middleware, then pass its dispatch function to setupListeners.
Standard RTK Query store configuration
Applications with custom browser lifecycle integration
Manual lifecycle integration
Call setupListeners with the Redux store's dispatch function, typically after configuring the store. This enables RTK Query's refetch-on-focus and refetch-on-reconnect behavior using the recommended defaults.
Follow-up: What if the application needs different browser-event behavior? Provide a custom handler as the second argument and use the supplied lifecycle actions to implement the desired wiring.
The function installs handlers for focus, visibility, online, and offline changes. Those handlers dispatch RTK Query internal actions, allowing subscribed queries to react to those environmental changes.
Follow-up: Which actions are available to custom handlers? The callback receives onFocus, onFocusLost, onOnline, and onOffline actions, and it must return an unsubscribe function.
setupListeners accepts the store dispatch and an optional custom-handler callback. The callback receives dispatch plus the focus and connectivity actions, so applications can control registration more precisely.
Follow-up: Can the lifecycle actions be dispatched outside the callback? Yes; the documentation says they are also exposed through api.internalActions.
refetchOnFocusrefetchOnReconnectapi.internalActionsonFocusonFocusLostonOnlineonOffline