Use Multiple Dispatchers on Flux Apps

Martín Bigio
2 min readApr 21, 2015

--

Flux has proved to be great for writing ReactJS applications. Within this architecture data flows on a single direction, from ActionCreators to Stores through a Dispatcher. When data gets updated on a store, it emits a change event which View components listen for. When they process this event, they update their internal state which kicks of React re-rendering process to update the UI.

Flux Architecture flow

So far so good. Say you want to implement a messaging application, just like Facebook’s web messenger. To do this, lets create a store to keep track of the messages we’re showing on the UI:

The MessageStore receives MessageActions. For now lets only implement the ADD action:

The actions are routed through the singleton AppDispatcher, which is based on Facebook’s open source dispatcher:

Finally, on some React component the user will trigger the action creator in response to some interaction:

Obviously, the messenger application needs way more actions, possibly, even more stores to keep other data concerns decoupled. As a consequence, the switch statement could potentially have many other cases. This shouldn’t be a problem though, a switch statement is easy to extend and understand, right?

For example, what if tomorrow you want to allow users to login and logout. To do so, you’ll have to introduce the LoginStore and LoginActions.

What if on top of the login feature you also want to allow the users to do something else, such as friending the people they mostly speak with? Again, you should introduce a new store and an action creator: FriendStore and FriendActions.

Since the dispatcher is a singleton, every action you trigger on any action creator will make each store to process them. Most stores will just skip them as they will bailout on the switch statement.

This is not only a waste of resources but also a bad practice as it could lead to weird bugs if you happen to reuse the same actions’ names on different action creators, just like I intentionally did on this example.

The problem is that whenever either a friend or message ADD action is triggered it will get processed by both stores!

We can avoid both this two issues by having separate dispatchers for each concern our application has: MessageDispatcher, FriendDispatcher and LoginDispatcher. Each of this should be singletons. For instance, the Message dispatcher could be implemented like as follows:

Finally, the action creators and the stores should get updated to use whichever dispatcher they need to:

Note that you shouldn’t abuse of this pattern and have a different dispatcher for every single pair of store/action creators. This should only be use when separating very different concerns your application has.

--

--