Why You Should Use React.js: An Introduction

Matt Hubert| June 18th
twitterfacebooklinkedin

Recently you’ve likely heard a lot of buzz about React.js, the new JavaScript library from Facebook that’s taking the web by storm.

Unfortunately, your first reaction (ha…) probably wasn’t “oh great, another JavaScript framework to learn!” If you’re like me, you held your head and cried “oh great, another JavaScript framework to learn…” And even though you’ve tried to ignore the hype and get back to work, if you’re being paid to build high quality modern web apps, staying current on every new piece of hotness is a full-time job. You’ve cut your teeth on Angular, been burned by Ember, and are sick of writing Backbone views. You were hoping that this whole React thing would just blow over, but React is here to stay. And thank goodness for that.

There are a dozen articles on how to get started with the framework, including its own very good documentation, so I’m not going to waste your time with that. Instead, I’d like to help you answer two-and-a-half specific questions:

  1. What makes React.js useful, and why should I care? (read: what’s all the hype about?)
  2. Should I use it over other frameworks? (read: yes)

So what makes React.js cool, anyway?

Its simplicity.

But seriously, you have a full-time job, and you do not have time to A) figure out the difference between a directive, scope, service, and module, and B) impart that knowledge to every new engineer who joins the project.

React.js does one thing, and one thing well: take data, and put it on the page.

If you have data, and you’d like it to display it in a template very easily, you’ll like React. If you want to change this data and have the page automatically update with no extra work, then you’ll love React. And if you’d like to do all of this after spending not more than ten minutes reading the docs, then you should just stop reading here and get started. I need not convince you further.

This introduces one of the most important things to keep in mind: React.js is not a full-fledged framework for building web apps. It’s often quoted as the “V” in MVC. Given this, React cannot be directly compared with, say, Angular, Ember, or Backbone; it only replaces the view / template aspect of those frameworks. You will still need to find a way to manage actually fetching data from the server. (More on our recommendation for that below.)

index.html

<html>
   <body>
       <div id=”users”></div>
   </body>
</html>

app.js

var Users = React.createClass({
   getInitialState: function() {
       return {users: []};
   },
   componentDidMount: function() {
      $.get(“/users”, function(users) {
          this.setState({users: users});
      }.bind(this);
   },
   render: function() {
       return (
           <div>There are {this.state.users.length} users in the system.</div>
       );
   }
});

React.render(
   <Users />,
   $(“#users”)[0]
);

 

OK, woah. A lot just happened there. I know I said it was simple, and I’ll admit that there’s still a bit to learn, but once you understand this example, you nearly understand the entire framework.

The first thing you’re probably wondering is: how did all of that HTML get into my JavaScript?! React.js uses a syntax extension called JSX that lets you pretend to write HTML to build your templates. It actually gets converted to JavaScript in the background (and then HTML again when it’s truly rendered), but you don’t need to worry too much about that.

Just imagine that instead of having your view reference a template file to render, you can just write the HTML directly in your JavaScript. (More about why that’s not actually insane, even though it may seem so at first, below.)

How the app works

React.createClass() creates a React component. Think of this like an atomic piece of functionality of your app, like a <Sidebar />, or a <UserList />, or a <NowPlayingButton />. These come with a template, and a bit of logic to render whatever’s necessary into the template.

Every time you make one, you assign it to a variable, which can then be referenced just like an HTML element (using JSX syntax) wherever you need it. So you can imagine an application that could look like:

<h1>Welcome!</h1>
<Navigation />
<div>
   <UserList />
</div>
<Footer />

Notice how we can easily combine HTML and JSX into one template filled with lovely reusable components. Every time you reference a component, its render() method will be called, which brings us to:

render() is called every time the component is referenced, and every time its state changes. render() takes the HTML that you plan on outputting to the page, which can include more React components of course (whose render() methods will then be called).

All React components have a property called this.state. Its default value is set by you by defining the getInitialState() method, and you can update it at any time by calling this.setState(). We do that in the componentDidMount() method we defined, which is another React built-in method that will be called once the component has rendered to the DOM.

And here’s the most important part: every time you call this.setState(), render() is called again automatically. That’s it. That’s the fundamental magic behind React.

The final piece is rendering the actual component to the DOM with React.render(). That is the entry point to your view getting rendered, and kicks off the following process:

  1. You call React.render() to render the <Users /> component to the DOM.
  2. React calls getInitialState() for you to set the initial value of the this.state property.
  3. React calls render() and outputs the contents into the DOM.
  4. React calls componentDidMount(), now that the component has been rendered to the DOM.
  5. This causes us to fetch the /users, and we set the component’s state with the new user list.
  6. Us calling this.setState() causes React to call render() again, updating the DOM with the new user count.

Pretty cool, eh?

Keep Passing that Data

What makes this even more interesting is that you can pass data from one element to the next, and every time the data changes, all components that use that data get re-rendered. Example:

var Users = React.createClass({
   // … getInitialState() and componentDidMount() from our previous example go here
   render: function() {
       return (
           <UserList users={this.state.users} />
       )
   }
});

var UserList = React.createClass({
   render: function() {
       return (
           <UserAvatar user={this.props.users[0]} />
       )
   }
});

var UserAvatar = React.createClass({
   render: function() {
       return (
           <img src={this.props.user.image_src} />
       )
   }
});

The only difference here is that once we get our users in our Users component, we pass them in as a property to another element, this time UserList and subsequently UserAvatar. All properties passed into a component are accessible via the this.props property.

Once this.setState() is called in the Users component, it triggers a cascading render effect: Users.render() being called causes UserList.render() to be called, which in turn causes UserAvatar.render() to be called, all receiving fresh data in the process.

And yes, this is actually performant. Thanks Facebook.

To summarize, the reason React.js is so useful is because it handles the most obnoxious part of any basic JavaScript application: It updates the DOM when your data changes. You just update your data in your model, and React will handle the rest. And, it does this using an extremely simple, intuitive API, meaning you and your engineering team can get up and running fast.

There are templates in my views!

A quick note on mixing HTML into your JavaScript. When I first saw it, I’ll admit that I was probably as skeptical as you are now. However, I’ve come to embrace this method of organization, and actually see it as superior to the old method.

The fact is, your templates are intrinsically linked to the view logic that defines and populates them. The two work together hand-in-hand, and often when one gets updated, so does the other.

Instead of having one big file with all of your HTML for the current page, and another with all of your JavaScript, imagine having multiple files each with a handful of related components: your navbars, your posts, your users, et cetera. Every time you want to edit a nav bar, you know that all of the functionality is exactly in one place.

How Does React.js Compare?

At Bitmatica, we feel that the simplicity of having all of our components separated into reusable modules, automatically updating themselves with the latest state as the data changes in the background, to be the future of application design. But it’s the ability to get up and running with the framework in just a few minutes that makes it our technology of choice.

However, as we’ve talked about, we still need to find a non-contrived way to get data from the server.

This makes React actually pair perfectly with Backbone. All of our applications are written in Backbone + React: We use Backbone for the fetching and management of our data and state, and React.js for displaying the data to the user. Backbone makes for a great router and model system, and React does the rest.

With Backbone and React together (along with the help of an excellent plugin), our example application gets even simpler:

app.js

var Collections = {};

Collections.User = Backbone.Collection.extend({
    url: "/users",
});

var Users = React.createBackboneClass({
   render: function() {
       return (
           <div>There are {this.getCollection().length} users in the system.</div>
       );
   }
});

var users = new Collections.User();

React.render(
   <Users collection={users} />,
   $(“#users”)[0]
);

users.fetch();

That’s the core of your entire app. Now with the help of the react.backbone plugin linked above, every time a collection or model syncs, any component that uses it is re-rendered. How great is that?

We’ll post a more in-depth article about how React and Backbone can work effectively together soon, but suffice to say, we believe that the simplicity and power that the two bring together is the most compelling JavaScript stack available today.

Interested in using React.js for your upcoming product, or training your team on how to build using the next generation of web technologies? Hire us!

Matt Hubert
Co-founder of Bitmatica. Super powers include catching falling objects and occasionally having perfect pitch.
Share
twitterfacebooklinkedin