Let’s Flux

Anirudh Ramanan
3 min readApr 29, 2017

--

Flux is not a library, or a framework. It is an architecture that Facebook uses internally while working with React, which follows the concept of unidirectional data flow.

The core idea of the flux architecture is the unidirectional flow of data in the application.

Flex consists of four major parts: Dispatcher, Stores, Views and Actions.

Actions: Actions are nothing but events that are fired from the views (or from other places as well) to the store. These actions flow via the dispatcher (we will cover dispatcher soon). Dispatcher exposes a way that allows us to fire an action to the store along with the data and type.

Eg: Consider a scenario where we want to make a network call on a buttonClick. We would create an action with signature of something like makeCall(). ActionCreators adds a type to the action so that the store can appropriately respond to the action. For this, action type could be MAKE_NETWORK_CALL.

Actions can also be fired from anywhere, eg when a network call response returns with a successful response, or an error code.

Stores: The store handles the application logic and manages all the data insertion methods, retrieval methods and dispatcher callbacks.

The stores registers its callback (which has action as a parameter) with the dispatcher. Store then updates itself based on the action it received via the dispatcher, and broadcasts an event that the state has been changed. The view then queries the store for the new state and updates itself.

Views: Views are just UI components that listen to the state change events, and queries the store for the new state. It then passes this on the its components for the rendering.

Dispatcher: It is the central hub of the architecture which manages all the data flow. It is nothing but a way of passing on actions to the stores. The store registers itself with the dispatcher and provides the callback which is used to receive the actions when the action creator provides a new action to the dispatcher.

Dispatcher provides the functionality of invoking the callbacks in a specific order. It also has the functionality to wait for other stores to complete updation before invoking callbacks on other stores.

In a nutshell, the dispatcher receives actions, and then dispatches the action along with the data to the registered callbacks.

This is how the flux architecture works.

Why Flux ?

  1. Help keeps your code clean. (Views are separate from the store logic)
  2. Due to the unidirectional data flow and the predefined responsibilities, the states are predictable and debugging becomes easier.

I hope you now have the basic idea of how the flux architecture works !

Resources ?

  1. Video : https://www.youtube.com/watch?list=PLb0IAmt7-GS188xDYE-u1ShQmFFGbrk0v&time_continue=621&v=nYkdrAPrdcw
  2. Github Repository: https://github.com/facebook/flux

--

--