I'm working on a chat application using react, redux and socket.io. As we know, redux is very helpful to pass down some state to deep and nested components. I like this idea to store some props as a redux state which will be passed down to some heavily nested component. I'm using socket.io-client library to create the socket object.
I need to pass down the created socket object to some heavily nested components so, I was thinking of creating the socket object on the redux state so that I can consume it easily on the nested components.
Is this a good approach or should I be doing something else?
The state in Redux is stored in memory. This means that, if you refresh the page the state gets wiped out. The state in redux is just a variable that persists in memory because it is referenced by all redux functions.
We connect the WebSocket server to the HTTP port when it's been created: const webSocketServer = require('websocket'). server; const http = require('http'); const webSocketServerPort = 8000; // Start the http server and the websocket server const server = http. createServer(); server.
No, it's not.
We recently added a Redux FAQ entry on where websockets should live in a Redux app. Quoting that entry:
Middleware are the right place for persistent connections like websockets in a Redux app, for several reasons:
- Middleware exist for the lifetime of the application
- Like with the store itself, you probably only need a single instance of a given connection that the whole app can use
- Middleware can see all dispatched actions and dispatch actions themselves. This means a middleware can take dispatched actions and turn those into messages sent over the websocket, and dispatch new actions when a message is received over the websocket.
- A websocket connection instance isn't serializable, so it doesn't belong in the store state itself
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