Flux in ReactJS
Flux is an application architecture but is not a library nor a framework. It is used internally in Facebook for building the client-side web application with React. There are three major roles that the Flux applications have while dealing with data: Dispatcher, Stores and Views (React components).
Advantages of Flux:
- It is easy to understand.
- It is open-source.
- It is more of a design pattern than a formal framework.
- It is easier to maintain.
- The parts of a flux application are decoupled.
- It complements React as view.
- It follows the concept of Unidirectional Data Flow model.
- It is useful when there is a necessity to keep the data updated in an effective manner, but the project has dynamic data.
- Runtime errors are reduced.
Structure and Data Flow:
The data flow is in a single direction or is unidirectional and is central to the flux pattern in a flux application. The various components of a flux architecture are:
Being the central hub for the React Flux application, the dispatcher manages the data flow of a Flux application. It can simply be understood as a registry of callbacks into the stores that have no real intelligence of its own. There are five dispatcher’s API methods.
|register()||To register a store’s action handler callback.|
|unregister()||To unregisters a store’s callback.|
|waitFor()||To wait for the specified callback to run first.|
|dispatch()||To dispatch an action.|
|isDispatching()||To check if the dispatcher is currently dispatching an action.|
The state and logic of an application are included in Stores. The behaviour of Flux Stores can be simply understood as those of the models in a traditional MVC. The Stores are also used for:
- maintaining a particular state within the application.
- updating themselves in response to an action.
- emitting the change event to alert the controller view.
Also known as controller-views, Views are React component which is used to store the logic, to listen to the change events, to receive the data from the stores and to re-render the application and is thus located at the top of the chain. The logic stored is used to generate actions and to receive new data from the store.
The data to the dispatcher is passed by an action creator or helper methods.