React – Flux Architecture

When applications grow and become large-scale, it becomes challenging to track, update, manage and share data with different components. For these reasons, Facebook created the flux architecture; It is a better way of structuring React Applications. Facebook internally uses it to scale its platforms by following its principles.

Flux is not a framework or a library, it is more of a concept. Although Flux library provides a few utility libraries to implement flux.

Features of Flux

Flux architecture has a few key features:

1. Unidirectional data flow.

Data can only flow in one direction. It cannot flow back from the view layer. This is in contrast to the MVC framework, where data can flow in both directions.

2. Decoupled State Management

It keeps the application state separate from our React Components. It is easier to maintain the state separately and also keeps our React components simple.

3. Predictable State

Flux provides a predictable state for the View (React Components). The data flows through a fixed pattern through four different flux components that we will look at later in this lesson.

Components of the Flux Architecture

Flux has four main components, where each has a unique purpose.

Action

An action starts and triggers the flux data flow. It tells the store what to do and which data to update.

Dispatcher

Its work is to broadcast and inform the store when a new action is received. There is only one dispatcher for the entire application.

Store

It is a collection of data(state) for the application. It performs any changes and updates to the data based on the action received. An application can have more than one store.

Controller View

The controller view is a React Component that is connected to the store and receives store updates. It can also create and send new actions to the dispatcher, which is why it’s called a controller.

Flux Data Flow

The four components of flux are connected, and data flows in one direction through it. The flow of data takes this order:

  1. The View dispatches actions on user interactions like button click. The dispatched action contains all the necessary details about the update that we want to perform.
  2. The dispatcher receives the action and forwards it to the store.
  3. The store then determines the type of action and uses the action’s payload to update its data collection/state/value.
  4. The View listens for any store updates and uses it to render the UI.

Now let’s find out how to structure and use the different components of the flux architecture.

Actions

An action is just a Javascript object. The action object has two properties according to the flux convention: type and payload.

type

It is a string value that is used to identify the action.

payload

A payload is any data that the store should use for updating its state. Some actions don’t need payloads, so it is optional.

For example, here is a sample action object to add an item to the ItemStore.

{
  type: 'ITEM_ADD',
  payload: {
  name: 'phone',
  price: '$500'
  }
}

ActionCreators

Action creators are helper functions used to create action objects. It is as simple as returning the action object from the function.

/* accepting parameters makes it reusable */
function addItem(item){
return {
      type: 'ITEM_ADD',
  payload: {
      name: item.name,
  price: item.price
  }
}
}
/* we can reuse addItem to create multiple action objects instead of typing action types and payload everytime */
const action1  = addItem({ name: 'phone', price: '$500' });
const action2 = addItem({ name: 'laptop', price: '$1500' });

Dispatcher

The action object that we created has to be passed to the dispatcher. The dispatcher is the bridge between actions and the store. Its main job is to take the created action object and broadcast it to all the stores registered with the dispatcher.

Dispatchers have a method to pass the action to it.

/* example on 'Add Item' button click dispatch the add item action */
  myDispatcher.dispatch(
  addItem({ name: 'phone', price: '$500' })
);

The addItem action creator will create the action object and send it to the dispatcher. Once it receives it, it will send this action to all the registered stores.

Store

A store should define all the necessary state/data to maintain them for the React application. Multiple stores are allowed to have a store for items, a store for users, etc.

Each store manages and updates its data collection when it receives the proper action object.

Registering the store with the dispatcher

Every store should register with the dispatcher to receive the action object.

MyStore.dispatchToken = myDispatcher.register(storeCallback);
  function storeCallback(action){
      switch(action.type) {
          case 'ITEM_ADD': 
  /* retrieve the item from action.payload and use it to update the store’s data */
          case 'ITEM_REMOVE':
              /* remove the data from the store */
          default: 
  /* do something if the action type is unexpected */
  }
}

The callback is the main part of the store that performs updates to the state/data. This store callback function is invoked by the Dispatcher when a new action is passed from the View as:

myDispatcher.dispatch(
    addItem({ name: 'phone', price: '$500' })
);

Emitting Events for the View

According to Flux Architecture, all stores must emit ‘change’ events and pass the updated data to the subscribed event listeners (of the View).

Without emitting any event on data updates, the store and the View will not sync with each other.

Controller Views

The controller views can add and store event listeners to detect any data changes in the store. When an event is fired from the store on any update, the controller view uses the updated data to modify its internal state. React Components that have the store event listeners are called controller views.

Summary

Flux is a Pattern or Architecture that is necessary for any medium or large-scale app. It provides important advantages for React applications over other architectures.

The are many libraries available that implement the flux architecture. The most popular one is the Redux State Management Library, which is widely used in most React projects.

Back to: React Tutorial > Advanced Topics in React

Leave a Reply

Your email address will not be published. Required fields are marked *