If, in React, I can use connect
to map state and dispatch to props, and the component I used connect
on will auto-render when the Redux state (and hence props) change, why would I ever need to use subscribe
?
subscribe(listener)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.
Using Redux for state management implies a trade-off. It introduces complexity, indirection and constraints into your code, which can be frustrating if there is no good reason for doing so. Using Redux also means learning how it works, which again could be a waste of time if you don't need it.
Often a large amount of code is required to make state management transparent, consistent and extensible. Additionally, the entry threshold in Redux is quite high, and understanding how action reductors and dispatches work can be quite overwhelming for beginners.
You're talking about Redux and Redux-React (which provides the connect
function, specifically for React components). Take a look at how Redux-React is implemented.
connect
is just a React specific abstraction over subscribe
.
What happens if you aren't using React? It's totally possible to use Redux with other frameworks or even just plain Javascript applications. In these cases, there needs to be a lower level mechanism for subscribing to changes in state.
They have also updated their documentation to speak to this regarding subscribe
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With