
React and Flux
Motivation
We’ve given Angular a good go on a number of projects but we are constantly coming up against problems using it.
With this in mind it is still beneficial to explore other options that will allow us to iterate faster and ultimately build better products for our clients.
Is React the answer?
alternatives
Angular 2.0
Backbone
Ember
Polymer
Flight
Meteor
React
Many others...
look busy
the future is coming

Web components are coming which will solve many of the problems of quickly being able to iterate by composition of elements/functionality.
But the spec is far from complete and general adoption amongst popular browsers will take a while.
We should prepare but we also need a solution for now.

React?
What is react?
JUST UI
STATEFUL
VIRTUAL DOM
DATA FLOW
CLASS-BASED
COMPONENT-BASED
LOVES ES6
UI LAYER
var HelloMessage = React.createClass({
render: function() {
return <div>Hello {this.props.name}</div>;
}
});
React.render(<HelloMessage name="John" />, mountNode);
React makes no assumptions about the rest of your technology stack, it can (fairly) easily be used as the V in MVC.
WTF???
Virtual DOM
var HelloMessage = React.createClass({
getInitialState: function() {
return {
name: 'Jack'
}
},
handleChange: function( newName ) {
this.setState({
name: newName
});
},
render: function() {
return (
<div>Hello <span class="highlight">{this.state.name}</span></div>;
)
}
});
React.render(<HelloMessage />, mountNode);
React uses a virtual DOM diff implementation for ultra-high performance.
React will calculate the least number of DOM manipulations to achieve the template changes.
stateful
var todoList = [ ... ];
this.setState({
className: 'open',
isOpen: true,
todos: todoList
});React is manipulated primarily via state.
By convention, states are applied to controller-views. When the state changes in a view the changes propagate down the element hierarchy.
This propagation results in the render method of children being called and diffs being calculated—if required. Empty function calls (or early returns) aren’t a performance concern, DOM manipulations are.
data flow
React implements one-way reactive data flow.
This data flow reduces boilerplate and makes it easier to reason about the intention of an application. Flux, a complementary library/architecture, runs with this premise by implementing dispatchers.
User intentions (or desired actions) are emitted (dispatched) as events. Any callbacks associated with the action are executed and it is the responsibility of the callback to decide actions to perform based on intention.
This restricts tight coupling, keeps logic close to action, increases composibility of elements and therefore code reuse and extensibility as well as reducing on/re-boarding costs.
component based
var People = React.createClass({
...
render: function() {
var peeps = this.props.people.values.map( function( peep ) {
return <li><img src={ peep.avatar.href } width="60" height="60" /></li>
};
return (
<ul>{ peeps }</ul>;
)
}
});
var Main = React.createClass({
...
render: function() {
return (
<div>
<h1>All the people</h1>
<People people={ this.state.people } />
</div>
)
}
});
React.render(<Main />, mountNode);
Encapsulate functionality, encourage loosely coupled components, make code intention clear.
Class based
var HelloMessage = React.createClass({
render: function() {
return (
<div>Hello <span class="large">{this.props.name}</span></div>;
)
}
});
React.render(<HelloMessage name="Johnson" />, mountNode);
Most modern JS frameworks are embracing JS's prototypical flavour of classical inheritance and class modelling. The new JS class syntax will (possibly) give more than just code convenience benefits to this approach.
The next React code iteration will use ‘native’ classes rather than the clunky `React.createClass`. So too will Polymer and Angular so Facebook certainly aren’t alone in this early adoption.
loves es6
React uses classes to define components, which is how Polymer and Angular 2.0 will also do it. Ember & Backbone have always had classes (of sorts).
Facebook also released a suite of transforms for using some ES6 (and 7) constructs today (compatible with IE8!).
Most immediately useful constructs are probably arrow functions for managing function scope in a class-based world and template literals for HTML stamping.
JSX?
return (
<div>
<TextInput onComplete={ this.onInput } />
<OutputPane />
<AnotherComponent />
</div>
)WTF??
JSX
JSX is not essential for React, but it does save a load of repetition and boilerplate.
JSX is similar to HTML.
In essence it simply allows you to write HTML in a neat and tidy manner in your code. If you like to keep your templates separate from code then have your code pull it in when necessary, although there are many reasons why Facebook have opted to keep templates in code.
JSX does require a compilation step, but your code is being built anyway right?

Flux?
what is flux?
Flux is actually a philosophy/architecture/pattern for building client web applications that utilises a unidirectional data flow.
The flow-based programming model is preferred, mainly to mitigate cascading changes inherent with two-way data binding, but also to make the system more predictable. Predictable state has a benefit for test-driven development as well.
Flux is not MVC, and the dispatcher, stores and views should not be confused with model-view-controller.
what is flux?
Application state is held within stores and actions, via the dispatcher, manipulate state.

Stores emit change events as they react to actions, views then respond to these changes in state.
dispatcher
var dispatcher = require( 'flux' ).Dispatcher;
var actions = require( '../actions' );
dispatcher.register( function( payload ) {
...
});
dispatcher.dispatch({
action: actions.ADD_PERSON,
person: { /* person object */ }
});
A base dispatcher class is provided by flux, it can be extended with additional functionality if required.
The dispatcher is the central hub for managing data flow.
It essentially is a registry of callbacks and has little real logic, although complex apps may have requirement for ordering certain dispatches. Mmm, promises.
stores
var EventEmitter = require( 'events' ).EventEmitter;
var dispatcher = require( './appDispatcher' );
class TodoStore extends EventEmitter {
constructor() {
dispatcher.register( /* an action */, this.onChange );
}
addListener( action, callback ) {
this.on( action, callback );
}
onChange( payload ) {
this.emit( payload.action, /* data */ );
}
};
Stores contain application state and logic.
Rather than a Model or a Collection, stores manage state for a particular application domain.
Stores react to actions and emit change events. Views listen to change events and react accordingly.
views and controller-views
var todoStore = require( './todoStore' );
var TodoComponent = React.createClass({
componentDidMount() {
todoStore.addListener( /* action */, /* callback */ );
}
...
render: function() {
...
}
});
React.render(<TodoComponent />, mountNode);
Views can be implemented how you like, but Reacts state management works well ;)
Views should react to store change events and be responsible for reacting to those events (and data) how they see fit. With React changes to state will propagate to any child components.

Pros
Flux is a skinny application architecture and, as such, is equally easy to implement in Angular/Polymer/whatever as it is in a project using React. Angular makes it very easy to pollute scope though, so be careful.
Many existing Angular (or otherwise) projects have swapped out their rendering mechanism to use React, as such it is a drop-in to handle the presentation layer.
Pros
Makes code intention clearer.
Encourages decoupled components.
Uses elements from modern computer science and application design and is future-prepared.
Angular 2.0 looks more like React than it does Angular 1.x, at least conceptually anyway. With 1600 Google apps being built using Angular 1.2/1.3 this is a big step for Google to make.
2015 is the year of the web component, anything that makes boarding that train easier should be a top priority for any organisation interested in efficiently producing stunning applications.
Pros
React handles DOM updates for you, you may be able to do it better for a particular app, but it’ll cost you.
HTML is old, and looks a little dog-eared faced with dynamic applications. JSX and reactive views help.
Building UI’s in code limits manual string concatenation, lessening surface area for XSS vulnerabilities.
As markup and logic are unified, Facebook argue that large apps become easier to extend and maintain.
Components become compose-able via states and property manipulation.
Atom (by Github) has access to the C++ DOM implementation and chose to use React, even adopting it half-way through development. (although shadow is coming).
Pros
From JSConf EU talk:
Decoupling and increased cohesion using a component model.
Abstraction, composition and expressivity.
Virtual DOM & synthetic events
- enables IE8 compatibility
- server-side rendering
- Testability
- Bindings to SVG, VML and <canvas>
cons
There is a learning curve and a natural inclination to say WTF is JSX.
React can be adopted anywhere but it’s much easier in an environment that supports commonJS modules. This will become native, until then it means using browserify. This is something we should be doing, but we haven’t currently explored it much in our stack.
Thinking about a flow-based architecture may not be obvious to all developers.
There is certainly a learning curve in getting used to managing state and child components.
cons
Style encapsulation is not considered, but only Polymer currently makes an effort at this (albeit a ham-fisted one).
It still isn’t web components.
You may prefer two-way data binding. It is possible using React, but not particularly pleasant. However, there is substantial criticism thrown at Angular regarding two-way binding and even Ember is moving to adopt one-way.
breakfast app?
References and links

Apps
http://facebook.github.io/flux/ (with video)
React and flux
Intro to React (vid)
the future and
react-complementary tech
I ragged on Angular 1.x a bit, here’s why
The road to Angular 2.0 and why
why you shouldn’t use angular (more two-way battering)
ng-europe chat - Angular 2 core (video)
Traceur Angular 2.0 will likely use this

thank you for listening
React and Flux
By Matt Styles
React and Flux
- 913