Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would I never need to use subscribe in Redux?

Tags:

reactjs

redux

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?

like image 551
ffxsam Avatar asked Jan 31 '16 06:01

ffxsam


People also ask

Why subscribe is used in Redux?

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.

What is one reason you might not want to use Redux in your project?

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.

Why not use Redux in React?

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.


1 Answers

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.

like image 199
Dan Prince Avatar answered Oct 13 '22 22:10

Dan Prince