Adds a change listener. It will be called any time an action is dispatched, and some part of the state tree may potentially have changed. You may then call getState()
to read the current state tree inside the callback.
You may call dispatch()
from a change listener, with the following caveats:
The listener should only call
dispatch()
either in response to user actions or under specific conditions (e. g. dispatching an action when the store has a specific field). Callingdispatch()
without any conditions is technically possible, however it leads to infinite loop as everydispatch()
call usually triggers the listener again.The subscriptions are snapshotted just before every
dispatch()
call. If you subscribe or unsubscribe while the listeners are being invoked, this will not have any effect on thedispatch()
that is currently in progress. However, the nextdispatch()
call, whether nested or not, will use a more recent snapshot of the subscription list.The listener should not expect to see all state changes, as the state might have been updated multiple times during a nested
dispatch()
before the listener is called. It is, however, guaranteed that all subscribers registered before thedispatch()
started will be called with the latest state by the time it exits.
It is a low-level API. Most likely, instead of using it directly, you'll use React (or other) bindings. If you commonly use the callback as a hook to react to state changes, you might want to write a custom observeStore
utility. The Store
is also an Observable
, so you can subscribe
to changes with libraries like RxJS.
To unsubscribe the change listener, invoke the function returned by subscribe
.
Arguments
-
listener
(Function): The callback to be invoked any time an action has been dispatched, and the state tree might have changed. You may callgetState()
inside this callback to read the current state tree. It is reasonable to expect that the store's reducer is a pure function, so you may compare references to some deep path in the state tree to learn whether its value has changed.
Returns
(Function): A function that unsubscribes the change listener.
Example
function select(state) { return state.some.deep.property } let currentValue function handleChange() { let previousValue = currentValue currentValue = select(store.getState()) if (previousValue !== currentValue) { console.log('Some deep nested property changed from', previousValue, 'to', currentValue) } } let unsubscribe = store.subscribe(handleChange) unsubscribe()
Please login to continue.