Where to have the socket object in your redux app?

2019-03-03 10:15发布

问题:

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?

回答1:

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