An Introduction to Flux

Flux is an application architcture invented by Facebook that is specifically for building client-side web applications. However, this application architecture can also be applied to React Native and the same methodologies can be applied to any rendering engine.

The main goal of Flux is that data flows one way.

Data Flow

Hacker Way: Rethinking Web App Development at Facebook

In Flux, data can only flow one way – e.i. Flux has unidirectional data flow. Data flows from an Action, to the Dispatcher, to the Store, to the View.

unidirectional data flow in Flux

When it comes to implementation, the Views listen to the Store for changes. When there is change, the view re-renders. When an Action comes in, it is really just added to a queue in the Dispatcher. The Dispatcher will apply Actions, and Actions will modify the Stores.

The Dispatcher

The dispatcher is the “central hub that manages all data flow in a Flux Application.” Stores register themselves with the Dispatcher, and Actions are queued on top of the Dispatcher. The job of the Dispatcher is to… well, dispatch. It dispatches the Actions to all the Stores that are registered with it.

Stores

Stores container the state of the app and logic for handling actions. The key difference between a Store and a traditional MVC model is that a Store handles the state of many objects. Stores handle a particular domain with the application. A Todo Store would manage all of the actions and data for tasks, completing a task, filtering tasks, and grouping tasks.

A store registers itself with the dispatcher and provides it with callbacks. So, if a Store can handle adding and deleting tasks, it would register add and delete callbacks with the Dispatcher.

Actions

An action is simply an object that represents some input data and an event type. This Action gets sent to the Dispatcher, which maps the Action’s data to Store callback’s that are registered with the given event type.

React

React acts as the view for applications using the Flux application structure. It is the most straight forward view rendering engine to get working with Flux.

React provides composable components that can have data passed to them. Using React, you can have many UI components passing data down to other UI components. All of this data would come from a few Containers that listen to data from the Stores.

Any event that a user causes in the app can be mapped to an Action that gets deployed to the Dispatcher.

Checkout the Flux documentation on Github.