Flux architecture

Aug 07, 2019

Understanding Flux

Flux is the application architecture from Facebook that complements React. It's not a framework or a library, but rather a solution to a common problem; how to build scalable client-side applications.

With the Flux architecture, we can rethink how data flows inside our application. Flux makes sure that all our data flows only in a single direction. This helps us reason about how our application works, regardless of how small or large it is. With Flux, we can add a new functionality without exploding our application's complexity.

You might have noticed that both React and Flux share the same core concept; one-way data flow. That's why they naturally work well together. We know how data flows inside a React component, but how does Flux implement the one-way data flow?

With Flux, we separate the concerns of our application into four logical entities:

  • Actions
  • Dispatcher
  • Stores
  • Views

Actions are objects that we create when our application's state changes. For example, when our application receives a new tweet, we create a new action. An action object has a type property that identifies what action it is and any other properties that our application needs to transition to a new state. Here is an example of an action object:

var action = {
  type: 'receive_tweet',
  tweet: tweet

As you can see, this is an action of type receive_tweet, and it has the tweet property, which is a new tweet object that our application has received. You can guess in which case this action is created by looking at its type. For each new tweet that our application receives, it creates a receive_tweet action.

Where does this action go? What part of our application gets this action? Actions are dispatched to stores.

Stores are responsible for managing your application's data. They provide methods for accessing that data, but not for changing it. If you want to change data in stores, you have to create and dispatch an action.

We know how to create an action, but how do you dispatch it? As the name suggests, you can use a dispatcher for this.

The dispatcher is responsible for dispatching all the actions to all stores:

  • It stores register with a dispatcher. They provide a callback function.
  • All actions are dispatched by a dispatcher to all the stores that are registered with it.

This is how our data flow looks like:

Actions > Dispatcher > Stores

You can see that the dispatcher plays a role of a central element in our data flow. All actions are dispatched by it. Stores register with it. All the actions are dispatched synchronously. You can't dispatch an action in the middle of the previous action dispatch. No action can skip the dispatcher in the Flux architecture.

Neeraj Dana

Experienced Software Engineer with a demonstrated history of working in the information technology and services industry. Skilled in Angular, React, React-Native, Vue js, Machine Learning