Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Getting Started with React

You're reading from  Getting Started with React

Product type Book
Published in Apr 2016
Publisher
ISBN-13 9781783550579
Pages 212 pages
Edition 1st Edition
Languages
Authors (3):
Doel Sengupta Doel Sengupta
Profile icon Doel Sengupta
Manu Singhal Manu Singhal
Profile icon Manu Singhal
Danillo Corvalan Danillo Corvalan
Profile icon Danillo Corvalan
View More author details

Table of Contents (18) Chapters

Chapter 6. Reacting with Flux

So far in the previous chapters, we have dug deep into the react world. Let's now explore the new dimension of react world, Flux, which is nothing but a unidirectional dataflow architecture. Flux is developed by the Facebook internal development team and is used in order to build client-side web applications at Facebook.

We will cover the following topics as we go along:

  • The synopsis of Flux versus the MVC architecture

  • Actions

  • Dispatchers

  • Stores

  • Controller-Views and Views

An overview of Flux


Flux should not be confused as a framework based on ReactJS. Flux is an architecture and is designed in order to reduce the complexity of a huge application built with Model View Controller (MVC) architecture and has been designed as an alternative of MVC.

The following are the different Flux components:

  • View—This is like for any web app, the views (basically the react component) receives the event and passes it to the Actions

  • Action—They are helper methods (actionCreators) that pass the data (payload) and actionType, received from an external API/view to a dispatcher

  • Dispatcher—These are Central hub of all registered callbacks. It receives the actions and acts as a "traffic controller" before it passes it to the Stores

  • Store—It is a data layer that stores all the computations and business logic. It is also responsible for storing the application state and the single source of truth for the application state. It receives the action from the dispatchers based on the registered...

Flux versus the MVC architecture


In a typical application built on the MVC architecture, the views get updated from the data, which is typically stored in the models. As the application grows, the number of models and views also grow, and there grows the interdependency among the various models. Therefore the views also get tdependent on multiple models, thus increasing the complexity of the application.

The interdependence of views and models can create diffraction in the source of truth, leading to increased application complexity and unpredictability. As a result, there needs to be a solution to internalize the control by moving all the control into the individual pieces.

Issue with a growing app built with MVC

Flux advantages

According to the Facebook Flux development team, the objects within a Flux application are highly decoupled, and adhere very strongly to the first part of the Law of Demeter: the principle that each object within a system should know as little as possible about the...

Actions


Actions are typically the data that enters into an application, either directly from the View or from an external Web API. Each action is nothing but a JavaScript method, which contains two parts: the actionType and the actual data. The actionCreators methods are simply discrete, semantic helper functions that facilitate passing data to the dispatcher in the form of an action. The different types of actions are declared as a JavaScript object, in a file named App-Constants.js. According to the Flux app hierarchy, the App-Contstants.js file resides under src/js/constants. Typical example for such a file looks like the following:

module.exports = {
        ADD_BOOK: 'ADD_BOOK',
        DELETE_BOOK: 'DELETE_BOOK',
        INC_BOOK_COUNT: 'INC_BOOK_COUNT',
        
DEC_BOOK_COUNT: 'DEC_BOOK_COUNT'
}

Here, ADD_BOOK, DELETE_BOOK are the actions.

Note

Actions, by itself, do not contain any functionality of their own. Actions are typically executed by the stores and are available in order to...

Dispatchers


As the name aptly defines, Flux dispatchers dispatches the actions to the subsequent stores. Dispatchers can be called as a registry of callbacks. All the stores are registered with the dispatchers.

Some key points of dispatcher are the following:

  • There is only one dispatcher per app.

  • Dispatchers being used as a center for all the registered callbacks.

  • It functions as a broadcaster of all the actions to the stores. Dispatchers acts as a queue, which sequentially broadcasts the actions. This is different from generic pub-sub systems in the following two ways:

    1. Callbacks are not subscribed to particular events. Every payload is dispatched to every registered callback.

    2. Callbacks can be deferred in whole or part until other callbacks have been executed.

  • The dispatcher has the capability to invoke the callbacks in the order specified, and it waits for other updates (waitFor() method does that).

  • In the flux library (npm install flux) node_module, the register() and dispatch() methods are defined...

Stores


Flux stores can be comparable with the models in MVC, though essentially they are not the same. From similar point of view, they are the same as all the business logic and computations happen in the Flux store. According to the Facebook team, "Stores manage the state of many objects—they do not represent a single record of data like ORM models do. Nor they are the same as Backbone's collections. More than simply managing a collection of ORM-style objects, stores manages the application state for a particular domain within the application."

Source https://en.wikipedia.org/wiki/Object-relational_mapping.

Object Relational Mapping (ORM) in computer science is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a "virtual object database" that can be used from within the programming language. In object-oriented programming, data management tasks act on object-oriented (OO) objects that are almost...

Controller-Views and Views


Views are primarily the React Views, which essentially generate the actions. Controller-View listens to our stores, for any changeEvent been broadcasted. The emitChange events let our Controller-Views know if any change has to be performed into the state of the view or not. They are essentially React components. In our code, we have five such react components, as follows:

  • app-addbooktoreadinglist.js

  • app-booklist.js

  • app.js

  • app-readinglist.js

  • app-removefromreadinglist.js

The following is the code for app-booklist.js:

var React = require('react');
var AppStore = require('../stores/app-stores');
var AddBookToReadingList = require('./app-addbooktoreadinglist')

function getLibrary(){
  return {items: AppStore.getLibrary()}
}

var BookList = React.createClass({
  getInitialState:function(){
    return getLibrary()
  },
  render:function(){
    var items = this.state.items.map(function(item){
      return (
        <tr key={item.id}>
          <td>{item.title}<...

Revisiting the code


In each of the React components (readingList and bookList), getInitialState() is initialized with the store public method getReadingList() and getLibrary(), respectively.

Various methods are executed at precise points in a component's lifecycle.

  • componentWillMount() is a React lifecycle method. It is invoked once, both on the client and server, immediately before the initial rendering occurs. If you call setState within this method, render() will see the updated state and will be executed only once despite change in the state:

    componentWillMount:function(){
        AppStore.addChangeListener(this._onChange)
      },
      _onChange: function(){
        this.setState(readingItems())
      }
  • Thus, componentWillMount() is listening to the addChangeListener (defined in the AppStore store). If the _onChange parameter is passed, then the current object (_this) is updated (setState) with the new/updated data/payload (readingItems).

  • In order to remove the items from the reading list, the event listener...

Summary


Through our libary_app application, we have explored how the unidirectional data flow in a simple Flux-based application. The users can see the booklist in the views. They can add books in the reading list, thus the actions (adding books ) gets passed to the dispatchers. Internally the dispatchers have the registered callbacks with the stores. The stores then adds/removes the books based on the user's action and computes the business logic and re-renders the changes accordingly again to the views.

In the next chapter, we will cover React good practices and patterns. This includes practices to develop reusable components, how to structure your components hierarchically to a better data flow, and how to validate your components behavior. In our app, we'll be improving our components developed so far.

lock icon The rest of the chapter is locked
You have been reading a chapter from
Getting Started with React
Published in: Apr 2016 Publisher: ISBN-13: 9781783550579
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime}