Action-driven side effects
Run analytics, persistence, notifications, or other side effects after a specific Redux action is dispatched.
Redux Toolkit · Module
Registers a listener entry on Redux Toolkit listener middleware. The supplied effect runs when exactly one configured action or state predicate matches, and the returned function removes that listener.
Call startListening with an effect and exactly one matching rule. The middleware checks each dispatched action against that rule; when it matches, it invokes the effect with the action and a listener API. The call returns an unsubscribe function that can remove the registered listener.
const startListening = (options: AddListenerOptions) => UnsubscribeListener| Name | Type | Description |
|---|---|---|
options | AddListenerOptions | Configuration object containing exactly one trigger selector and the effect callback; the selector may be type, actionCreator, matcher, or predicate. |
UnsubscribeListener
import { createListenerMiddleware, createAction } from '@reduxjs/toolkit'
const listenerMiddleware = createListenerMiddleware()
const increment = createAction<number>('counter/increment')
listenerMiddleware.startListening({
actionCreator: increment,
effect: async (action, listenerApi) => {
console.log('Incremented by', action.payload)
listenerApi.cancelActiveListeners()
},
})This registers an effect that runs whenever the increment action creator matches a dispatched action.
Run analytics, persistence, notifications, or other side effects after a specific Redux action is dispatched.
Coordinate workflows that wait for later actions, delays, or state conditions inside an effect.
Observe a state transition by comparing current and previous state in a predicate.
It registers a listener entry on the middleware and returns an unsubscribe function. The entry contains an effect plus exactly one condition: type, actionCreator, matcher, or predicate.
Follow-up: How would you remove a statically registered listener? Call the returned unsubscribe function.
The effect receives the matched action and listenerApi, and it may be synchronous or asynchronous. listenerApi provides middleware operations such as dispatching, reading state, delaying, and cancellation.
Follow-up: How can a listener react to state changes rather than a particular action type? Use predicate and compare the current and previous state.
Use actionCreator for an exact Redux Toolkit action-creator match, matcher for matching among multiple actions, type for an exact string type, or predicate for a custom action-and-state test. Exactly one of these four options is required.
Follow-up: When would matcher be preferable to actionCreator? Use matcher when several action creators share a condition, commonly through an RTK matcher helper.
createListenerMiddlewareaddListenerremoveListenerListenerApiListenerPredicateMatcher