Where should long running processes "live" in a react+redux app?
For a simple example, consider a class which sends and receives messages over a websocket:
class WebsocketStreamer { sendMessage(message) { this.socket.send(…); } onMessageReceive(event) { this.dispatch({ type: "STREAMER_RECV", message: event.data, }) } }
How should the lifecycle of this class be managed?
My first instinct is to keep it on the store
:
var stores = { streamer: function(state={}, action) { if (action.type == "@@INIT") return { streamer: new WebsocketStreamer() } if (action.type == "STREAMER_SEND") state.streamer.sendMessage(action.message) return state; } }
But, aside from being a bit strange, there's also no way for the WebsocketStreamer
to get access to the dispatch()
function, and it breaks hot reloading.
Another potential solution is to keep it in a global somewhere:
const streamer = new WebsocketStreamer();
But that has obvious testability implications, and breaks hot reloading too.
So, where should a long running process live in a react + redux app?
Note: I realize that this simple example could be built with just stores + action providers. But I would specifically like to know where long-lived processes should exist in situations where they exist.
The state in Redux is stored in memory, in the Redux store. This means that, if you refresh the page, that state gets wiped out. The state in redux is just a variable that persists in memory because it is referenced (via closure) by all redux functions.
Redux follows the unidirectional data flow. It means that your application data will follow in one-way binding data flow. As the application grows & becomes complex, it is hard to reproduce issues and add new features if you have no control over the state of your application.
Redux is a JavaScript library that depicts how an application's state should be managed and accessed. It supports state management via a centralized store. Though there are many libraries like Flux that support state management, data flow in Redux is clear and easier to integrate.
While it's certainly possible for each of these to become a performance concern in sufficiently complex situations, there's nothing inherently slow or inefficient about how Redux is implemented.
In my experience, there are two options. First, you can pass store to any non-Redux code and dispatch actions from here. I've did this with socket connection and all was fine. Second, if you need socket or whatever to change with redux actions, it looks like a good idea to put connection and it's management in custom middleware. You'll have access to store API as well as will be informed on all actions dispatching, so could do anything you need to.
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