Life as a developer

React – Should you even bother?

A couple of weeks ago I was asked to hold a 30-minute talk for NNUG, a Norwegian .net user group. My topic of the day was React. I have been using React for a couple of months now, creating a mobile app together with Phonegap. I have previously held talks about Angular based on my experience with several Angular applications. Having experience in both, as well as several other MV* JavaScript frameworks, I was able to make comparisons and offer the attendees a few of my insights.

blog02_small It is easy to be intrigued by new frameworks, and I myself have fallen victim to this. When I first started using Angular, I was excited learn the framework. In the process I let all the fancy features overshadow my struggles with the framework. So when I was brought into this project, I had a more healthy skepticism (to be honest, I was more like, “Oh no, not yet another framework to learn!”). I had invested a lot of time in order to learn Angular, and I felt like I had finally figured out how it worked. So why bother investing another large bulk of time, just to end up at approximately the same place? Now, two months later, I can say that the time I spent learning React was neither as long as I initially feared nor a total waste.

React
React is a JavaScript library for building user interfaces. You can use React as the V in MVC. Because React does not make any assumptions in regards to your technology stack, you might try it for a small feature in your existing project. Another awesome aspect about React is that for ultra-high performance, it uses Virtual DOM. It can also render on the server using Node.js, meaning that no heavy browser DOM is required. React.js implements one-way reactive data flow, and this reduces boilerplate and is also easier to reason about than traditional data binding.

Mixing your markup and JS

React is the result of a combined effort from the development teams of Facebook and Instagram. Facebook is using React components for more and more features on its web client, while Instagram has built its web client with React in its entirety. The main benefit of migrating Instagram from the standard Mustache/Backbone/jQuery trio to React was being able to use expression of display logic with pure JS, as well as the standard object-oriented principles together with procedural techniques. With it, they were able to reuse code and use functional concepts like map and filter. Also, React was used to render the UI, rather than relying on the primitives provided by Mustache. They went from fighting with Mustache, to React, where they could use JavaScript (which is far more powerful than any templating language) for building the UI. It is also easy for designers to contribute, thanks to JSX, a syntax which is similar to HTML.

Built on familiar concepts

React aims to introduce as few concepts as possible. Instead, React uses familiar idioms and concepts that we developers already have a clear understanding of. One of the brains behind React, Pete Hunt ([@floydophone](https://twitter.com/floydophone)), is not a big proponent of huge frameworks that try to do everything.

The framework cannot know how to separate your concerns for you. It should only provide powerful, expressive tools for the user to do it correctly.

And React might just be the perfect tool for the job. It removes some of the magic from the equation and shortens the time spent on learning. Thinking back to the time I was learning Angular, I initially struggled to get a really good grasp of it all, even after reading several books and blog posts.

Re-rendering the whole application when data changes

It was only a while back when the standard was server-rendered web apps, where users had to hit the refresh button to see fresh data after it had changed on the server. This did not require you to scuffle around with writing custom codes that would bring the view up-to-date with the state of the data. Now it is more common to let JavaScript refresh the page, as server-side refreshing is slow and you lose the state of the application. React actually brings out this particular conceptual model to JS apps in a way that makes for a fast rendering, while also maintaining the state of the UI. Before React, Instagram had an issue with templates. Template languages express the initial render of your application and this makes you responsible for manually mutating the state of the UI whenever your backing data changes and events occur. With React, it manages the UI updates for you automatically, meaning that you do not have to do it yourself.

### Implementation of the DOM and events

React is fast and efficient and its apps can run easily at 60fps, even on mobile devices. Because React deals with only a fake DOM, it can transparently render on the server, which makes it possible to do all of your HTML generation in Node. All the HTML comes from components, and they are the one thing you really have to learn, but do not worry – they are easy to learn and easy to work with. A component is really just a regular JavaScript class, created with React.createClass (or you can use ES6 Classes as of v0.13).

Given a HTML file (index.html) like this:


<body>
    <div id="container"/>
</body> 

and a React component (Main.jsx):


var Main= React.createClass({
…
}); 

You can inject your React app like this (in your app.js):


React.render(<Main/>, document.getElementById("container"));
Components

A basic React component (Person.jsx):


var Person = React.createClass({
    onClickPerson: function(id) {
        routie("person/" + id); // using routie.js for routing
    },
    render: function() {
        var person = this.props.person;
        return (
            <a onClick={this.onClickPerson.bind(this, person.id)}>
                <h4>{person.name}</h4>
            </a>
        );
    }
}); 

There are several functions supported by React (see full spec), but the only function that is required is render(), which is responsible for returning what to display. You can see the JSX syntax within the parentheses of the return statement. You are also free to add your own functions, of course, as you can see here with onClickPerson:.

Properties

Building on this component, we are now ready to add data. In React, data is managed either through properties or the state. You use properties for data that is immutable (does not change), and you put data that can change into the state of the component.


var Person= React.createClass({
    propTypes: {
        person: React.PropTypes.object.isRequired
    },
    getDefaultProps: function(){
        return { partner: undefined };
    },
    onClickPerson: function(id) {
        routie("person/" + id);
    },
    render: function() {
        var person = this.props.person;
        return (
            <a onClick={this.onClickPerson.bind(this, person.id)}>
                <h4 {person.name}</h4>
            </a>
        );
    }
}); 

Here you see data added using properties; they are made accessible through this.props.<key>. You can use a propTypes function to ensure that the components are set up with the correct properties. If not, warnings will turn up in your console. By using the getDefaultProps function, you can set default values for your properties. To use this component, you would set it up like this:

<Partner partner={this.partner} />
State

If you are working with data that is mutable, you have to use state to manage your data.

Search.jsx:


var Search = React.createClass({
    getInitialState: function() {
        return { searchText: '' };
    },
    handleSearchInput: function(e) {
        this.setState({ searchText: e.target.value});
    },
    render: function () {
        // searchLogic here ...
        return (
            <div>
                <Input type="Search"
                value={this.state.searchText}
                    placeholder="Search ..." 
                    onChange={this.handleSearchInput}/>
                ... // search results
            </div>
        );
    }
}); 

getInitialState is another function used by React. It is run once and sets up the initial state (duh). You can see from this component how you can get data from the state (this.state.<key>) and how to update the state with new data (this.setState({object})). Note that you should only update the state through the setState function. When setState is called, React will re-render all your components by calling each component’s render function. You might think that this is extremely expensive, but trust me, thanks to the Virtual DOM, it is fast and it works.

Mixins

As you often have functionality that you want to share across your components, you need an easy way to do that. This is where mixins come into play. You can create a regular JavaScript file with the functionality you want to share.

FormatUtils.js:


var FormatUtils = {
    formatMobile: function(mobile) {
        return mobile.substring(0,3) + ' ' 
            + mobile.substring(3,5) + ' ' 
            + mobile.substring(5,8);
    }
}

If you want to use the formatMobile function in one of your components, you will need to specify FormatUtils as one of the mixins you want to include in your function.

ContactView.jsx:


var contactView = React.createClass({
    mixins: [FormatUtils],
 
    render: function() {
        var mobileFormatted = this.formatMobile(mobile);
        return (
            <div>{mobileFormatted}</div>
        );
});

As you can see, the functions on a mixin, is available on this, as if the mixin was a part of the component. Also note that a mixin can hook into a component’s lifecycle, by adding lifecycle functions to the mixin.

This covers the basics of React. Go to Reacts homepage for the details. Get a hold of React today and you will be glad that you did!

Resources:

goldnarms

Arnstein Johansen is a .NET Developer with a speciality in web development, but he also dabbles in mobile development and everything new and exciting. Arnstein works for Itema AS, a mid-size consultant agency in Trondheim. Itema has 25 consultants and recently won the prize for Norway's best workplace. He likes to share his knowledge by holding talks for others, either it is clients, colleagues or likeminded developers in user groups. He has hands-on experience from large projects, the latest from Urørt where he leads a team of developers creating a music service used by around 100000 users.

One Comment

  1. Pingback: 1p – React – should you even bother | blog.offeryour.com

Leave a reply