Flux Pattern Explained
What is the Flux pattern?
Following Facebook’s definition, Flux is an application architecture that can be used for building frontend web applications. The intent of this pattern is to enforce a unidirectional flow of data between a system’s components, using events. Flux has 4 main components, namely Action, Stores, Dispatcher, and View:
View: The Views are controller-views. They listen to change events raised from the store, and re-renders appropriately. Views can add new actions to the dispatcher on user interactions.
Action: Actions are simple objects with some data and are created by the view.
Dispatcher: Dispatcher acts as a central hub, it receives all actions from the view and propagates them to the store.
Store: Store contains the application’s state and logic. It receives an update event from Dispatcher and will respond to it.
As every change must go through the dispatcher via actions, instead of bidirectional communication between components, this enforces unidirectional flow.
Application of the Flux pattern
Let’s consider an example of a chat application which employs a Flux architecture and an user interaction which involves a user A sending a message to a user B. The diagram below outlines the interaction between the components in the Flux architecture for this example.
When User A sends a new message in a chat with User B on his own Chat Tab view, the Chat Tab View of User A will propagate this interaction to the Dispatcher as a create message action. The Dispatcher will receive the action from the sender’s view, and send a create event to the Messages store. The Store will add the new message into the chat between the 2 users and send the change event to update 2 Views, both the sender’s and receiver’s View. Both the Chat Tab Views of both the sender and receiver, which are User A and B respectively, receive the change event and re-render themselves. If any user wants to send a new message, it will be processed after the action generated by the previous message has been processed, and it will go through the same Dispatcher.
Flux is a state management pattern by allowing components to communicate through events and using actions with the dispatcher. This allows for more predictable interactions, especially in cases where views can create actions that will update many stores and stores can trigger changes that will update many views.
However, the drawback of Flux is that the code required to set up this architecture is not trivial, hence if the application is a simple application with already predictable interactions, the effort may not be worth it.
I hope that you have gained better insight of Flux architecture from reading this article. Thank you.