A Look at Facebook's React

15 Aug 2013 | By Alex Young | Tags frameworks facebook ui reactive

React

React (GitHub: facebook / react, License: Apache 2.0, npm: react-tools, bower: react) from Facebook and Instagram is a UI framework. It’s maintained by Paul O’Shannessy, and Paul and Christopher Chedeau both post to the React blog regularly about new features and community news.

React is meant to be a declarative framework, so it focuses on transforming data into interface components. Data can come from servers and user input – there’s no specific transport layer support, instead other libraries like jQuery are relied on.

The first thing you’ll notice about React is it mixes HTML and JavaScript:

var HelloMessage = React.createClass({
  render: function() {
    return <div>{'Hello ' + this.props.name}</div>;
  }
});

React.renderComponent(<HelloMessage name="John" />, mountNode);

What’s going on? Well, this snippet is intended to be placed inside a script tag, with the type attribute set to text/jsx. JSX is React’s XML-based template language. It doesn’t hit the DOM until it needs to: instead a mock DOM, or faked browser is used to maintain an in-memory representation of your templates. Be aware that this comes with caveats: everything is escaped by default, so HTML entities can easily be double escaped.

You don’t need to use JSX, however: React.DOM.div({}, 'Hello ' + this.props.name) is equivalent to the previous example.

Applications made with React are based on components. Components are created with React.createClass method (not React.createComponent). Components have a “state” and “props”: the state is private, and mutable. If the state is updated, then the component will be re-rendered: this is known as reactive state, and is how React models reactive data flows. React doesn’t re-render the entire component, it tries to only render what changed:

render() methods return a description of the DOM, and React can diff this description with the in-memory representation to compute the fastest way to update the browser.

React plays well with Node-based build systems: there’s a Grunt task for building JSX, in case you don’t want to render everything in the browser. The documentation has a section on React’s tooling integration.

The documentation for React is straightforward and easy to follow: there’s a tutorial that introduces the main aspects of the framework. It’s difficult to say how it compares to other frameworks like AngularJS, but I like the distinction between mutable and immutable state and properties for modeling reactive data flows.


blog comments powered by Disqus