Flux architecture~ Popular concepts ~

Flux architecture

Flux architecture is one of those popular things that the ecosystem replaces with something new. Back in the early days of React, this pattern was the answer to many questions. Facebook's framework came with a couple of brilliant ideas, but one thing was missing - how and where we manage state. Facebook answered - Flux architecture.

The idea is to keep our state in multiple stores. A dispatcher receives actions, and it forwards them to each of the stores. Internally the store decides whether the action makes sense. Maybe it changes its state, maybe not. In case of a change, it notifies the views (React components).

In this chapter, we will implement the pattern. Let's start by writing the dispatcher.

const D = (function () {
  const stores = [];
  return {
    register: function (store) {  
      stores.push(store);
    },
    dispatch: function (action) {
      stores.forEach(function (s) {
        s.update(action);
      });
    }
  }
})();

There are dozen of Flux libraries and, in most of them, the dispatcher has such API. One method for registering a store and another for dispatching actions. We assume that the stores will have an update method. That is the function that will receive the action.

To make the example a bit more interesting we will use two stores. Let's say that we have a stream of data. The first store will collect only numbers and the second one only letters. The view will be just a simple function displaying what's in both stores.

const Numbers = {
  data: [],
  update(action) {
    if (typeof action.payload === 'number') {
      this.data.push(action.payload); renderView();
    }
  }
}
const Letters = {
  data: [],
  update(action) {
    if (typeof action.payload === 'string') {
      this.data.push(action.payload); renderView();
    }
  }
}
function renderView() {
  console.log(Numbers.data, Letters.data);
}

In the end, we have to dispatch some actions:

D.dispatch({ payload: 'A' }); // [], ['A']
D.dispatch({ payload: 'B' }); // [], ['A', 'B']
D.dispatch({ payload: 5 }); // [5], ['A', 'B']
D.dispatch({ payload: 'C' }); // [5], ['A', 'B', 'C']
D.dispatch({ payload: 6 }); // [5, 6], ['A', 'B', 'C']

The most important characteristic is that the data flows in one direction. The actions are getting fed to the stores. If the state changes, the views are re-rendered.