Reader small image

You're reading from  React.js Essentials

Product typeBook
Published inAug 2015
Reading LevelIntermediate
PublisherPackt
ISBN-139781783551620
Edition1st Edition
Languages
Right arrow
Author (1)
Artemij Fedosejev
Artemij Fedosejev
author image
Artemij Fedosejev

Artemij Fedosejev is a technical lead living in London, United Kingdom. He is a self-taught web developer who has been a web developer since the early 2000s. Artemij earned his BSc in computer science from University College Cork, Ireland. He participated in the IGNITE Graduate Business Innovation Programme, where he built and launched a website that received the Most Innovative Project award. Artemij has played a key role in creating frontend architecture using React.js and Flux for various websites. Artemij created a number of open source projects, including Snapkite Engine, Snapkite Stream Client, and other projects.
Read more about Artemij Fedosejev

Right arrow

Chapter 9. Supercharge Your React Architecture with Flux

The process of building a web application has one quality that somewhat mirrors the process of evolution of life itself; it never ends. Unlike building a bridge, building a web application has no natural state that represents the end of the development process. It's up to you or your team to decide when you should stop the development process and release what you've already built.

In this book, we reached that point at which we can stop developing Snapterest. Right now, we have a small React.js application with a basic functionality that simply works.

Isn't that enough?

Not exactly. Earlier in this book, we discussed how the process of maintaining your web application is much more expensive in terms of time and effort than the process of developing it. If we choose to finish developing Snapterest at its current state, we'll also choose to start the process of maintaining it.

Are we ready for maintaining Snapterest? Do we know if its current...

Analyzing your web application's architecture


To answer these questions, let's zoom away from the implementation details and explore our application's architecture:

  • The app.js file renders our Application component

  • The Application component manages a collection of tweets and renders our Stream and Collection components

  • The Stream component receives the new tweets from the SnapkiteStreamClient library and renders the StreamTweet and Header components

  • The Collection component renders the CollectionControls and TweetList components

Stop right there. Can you tell how data flows inside our application? Do you know where it enters our application? How does a new tweet end up in our collection? Let's examine our data flow more closely:

  1. We use the SnapkiteStreamClient library to receive a new tweet inside a Stream component.

  2. This new tweet is then passed from Stream to the StreamTweet component.

  3. The StreamTweet component passes it to the Tweet component, which renders the tweet image.

  4. A user clicks on that...

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...

Creating a dispatcher


Now let's implement this data flow. We'll start by creating a dispatcher first. Facebook offers us its implementation of a dispatcher that we can reuse. Let's take advantage of this.

  1. Navigate to the ~/snapterest directory and run the following command:

    npm install --save flux
    

    The flux module comes with a Dispatcher function that we'll be reusing.

  2. Next, create a new folder called dispatcher in our project's ~/snapterest/source/dispatcher directory. Now create the AppDispatcher.js file in it:

    var Dispatcher = require('flux').Dispatcher;
    module.exports = new Dispatcher();

First, we import Dispatcher provided by Facebook, then create, and export a new instance of it. Now we can use this instance in our application.

Next, we need a convenient way of creating and dispatching actions. For each action, let's create a function that creates and dispatches that action. These functions will be our action creators.

Creating an action creator


Let's create a new folder called actions in our project's ~/snapterest/source/actions directory. Then, create the TweetActionCreators.js file in it:

var AppDispatcher = require('../dispatcher/AppDispatcher');

function receiveTweet(tweet) {

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

  AppDispatcher.dispatch(action);
}

module.exports = {
  receiveTweet: receiveTweet
};

Our action creators will need a dispatcher to dispatch the actions. We will import AppDispatcher that we created previously:

var AppDispatcher = require('../dispatcher/AppDispatcher');

Then, we create our first action creator receiveTweet():

function receiveTweet(tweet) {

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

  AppDispatcher.dispatch(action);
}

The receiveTweet() function takes the tweet object as an argument, and creates the action object with a type property set to receive_tweet. It also adds the tweet object to our action object, and now every store...

Creating a store


As we learned earlier, stores manage data in your Flux architecture. They provide that data to the React components. We're going to create a simple store that manages a new tweet that our application receives from Twitter.

Create new folder called stores in our project's ~/snapterest/source/stores directory. Then, create the TweetStore.js file in it:

var AppDispatcher = require('../dispatcher/AppDispatcher');
var EventEmitter = require('events').EventEmitter;
var assign = require('object-assign');

var tweet = null;

function setTweet(receivedTweet) {
  tweet = receivedTweet;
}

function emitChange() {
  TweetStore.emit('change');
}

var TweetStore = assign({}, EventEmitter.prototype, {

  addChangeListener: function (callback) {
    this.on('change', callback);
  },

  removeChangeListener: function (callback) {
    this.removeListener('change', callback);
  },

  getTweet: function () {
    return tweet;
  }

});

function handleAction(action) {
  if (action.type === 'receive_tweet...

Summary


In this chapter, we analyzed our React application's architecture. We learned about the core concepts behind the Flux architecture, and implemented a dispatcher, action creator, and a store. In the next chapter, we'll integrate them into our React application and get its architecture ready for a maintenance paradise.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
React.js Essentials
Published in: Aug 2015Publisher: PacktISBN-13: 9781783551620
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.
undefined
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 AU $19.99/month. Cancel anytime

Author (1)

author image
Artemij Fedosejev

Artemij Fedosejev is a technical lead living in London, United Kingdom. He is a self-taught web developer who has been a web developer since the early 2000s. Artemij earned his BSc in computer science from University College Cork, Ireland. He participated in the IGNITE Graduate Business Innovation Programme, where he built and launched a website that received the Most Innovative Project award. Artemij has played a key role in creating frontend architecture using React.js and Flux for various websites. Artemij created a number of open source projects, including Snapkite Engine, Snapkite Stream Client, and other projects.
Read more about Artemij Fedosejev