Skip to content

Commit 67be74b

Browse files
committed
Document adding listeners inside components
1 parent 57ff9c0 commit 67be74b

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

docs/api/createListenerMiddleware.mdx

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -699,3 +699,33 @@ listenerMiddleware.startListening({
699699
},
700700
})
701701
```
702+
703+
### Adding Listeners Inside Components
704+
705+
Listeners can be added at runtime via `dispatch(addListener())`. This means that you can add listeners anywhere you have access to `dispatch`, and that includes React components.
706+
707+
Since dispatching `addListener` returns an `unsubscribe` callback, this naturally maps to the behavior of React `useEffect` hooks, which let you return a cleanup function. You can add a listener in an effect, and remove the listener when the hook is cleaned up.
708+
709+
The basic pattern might look like:
710+
711+
```js
712+
useEffect(() => {
713+
// Could also just `return dispatch(addListener())` directly, but showing this
714+
// as a separate variable to be clear on what's happening
715+
const unsubscribe = dispatch(
716+
addListener({
717+
actionCreator: todoAdded,
718+
effect: (action, listenerApi) => {
719+
// do some useful logic here
720+
},
721+
})
722+
)
723+
return unsubscribe
724+
}, [])
725+
```
726+
727+
While this pattern is _possible_, **we do not necessarily _recommend_ doing this!** The React and Redux communities have always tried to emphasize basing behavior on _state_ as much as possible. Having React components directly tie into the Redux action dispatch pipeline could potentialy lead to codebases that are more difficult to maintain.
728+
729+
At the same time, this _is_ a valid technique, both in terms of API behavior and potential use cases. It's been common to lazy-load sagas as part of a code-split app, and that has often required some complex additional setup work to "inject" sagas. In contrast, `dispatch(addListener())` fits naturally into a React component's lifecycle.
730+
731+
So, while we're not specifically encouraging use of this pattern, it's worth documenting here so that users are aware of it as a possibility.

0 commit comments

Comments
 (0)