The Mental Model That Finally Helped Me Understand ReactJS

TL;DR I struggled for a long time trying to understand React. This is what I wish someone had told me.

What is React?

How does React compare to Angular, Ember, Backbone, et al? How do you handle data? How do you contact the server? What the heck is JSX? What is a "component"?

Stop.

Stop it right now.

React is MAINLY THE VIEW LAYER.

React is mentioned in the same breath as other Javascript frameworks, but "React vs Angular" doesn't make sense because they aren't directly comparable. Angular is a complete framework (including a view layer), React is not. This is why React is confusing to understand, it's emerging in an ecosystem of complete frameworks, but it's mostly the view.

React gives you a template language and some function hooks to essentially render HTML. That's all React outputs, HTML. Your bundles of HTML / Javascript, called "components," can have their own internal state (such as which tab is selected in a tab view), but in the end you just barf out HTML.

You can't build a fully functional dynamic application with React alone. We'll learn more about why below.

The Good

After working with React for a while, I've seen some important benefits surface.

1. Easily reason about how views render

Your user logs in and you have to update the header. You might do this:

<header>
    <div class="name">
        Not Logged In
    </div>
</header>
$.post('/login', credentials, function( user ) {
    // Modify the DOM
    $('header .name').text( user.name );
});

This is "imperative" programming. You're telling the browser how to update in a series of steps. In a complex application, I can tell you from experience, this code doesn't scale. How do you debug the output? How do you know who updated the header? Who else has access to the header HTML? Who holds the source of truth for the name being visible? This DOM manipulation is just as bad as a GOTO statement for reasoning about your program.

Here's how you might do it in React:

render: function() {
    const name = this.state.name;
    return <header>
        { name ? name : <span>Not Logged In</span> }
    </header>;
}

Yes, JSX looks weird at first, but humor me. We can tell instantly how this component will render. If you know the state, you know the rendered output. You don't have to trace program flow.

This is "declarative" programming. You declare that you want a header with a name or a message. You don't tell the computer how to do it, like in the jQuery example. In jQuery, you mutate the DOM over multiple steps and can't reason about how it got that way.

2. JSX means clean, well organized view code

The weird mix of HTML / Javascript soup above might make you cringe. We've been conditioned to not put raw Javascript in the DOM (like onClick handlers) since we were wee developers. You'll have to trust me, though; working with JSX components is really nice.

The most common React misconception is that JSX violates separation of concerns. We're mixing logic and views, right?

Hang on. "Logic" isn't a concern. You're thinking of "business logic:" rules about updating your data. None of that lives in React. View logic, like whether or not you show the name in the header, is obviously part of the view concern. We used to separate HTML templates from Javascript, even though they're both part of the view concern. After working with React, you'll learn there's no need for that pattern, and you'll stop fearing "logic" in your templates (yes, Mustache.js got it wrong!).

3. You can render React on the server

Server side rendering is one of the most important optimizations you can make to speed up a Javascript application. Browsers are designed from the ground up to show users rendered HTML as fast as possible.

True "single page applications" are only appropriate for a subset of the web, like email clients where you typically leave them open for weeks and do very few actual page loads.

Angular and others encourage you to do things like render your page with PhantomJS and serve that to search engine crawlers based on user agent, or pay cash money for that as a service. Yuck!

Server rendering with React isn't free, but once implemented, it's a breath of fresh air. I've done this for my web app ShaderFrog, and even on a nano EC2 instance, it loads quite fast.

4. React will trick you into loving functional programming.

React works well with functional, pure, immutable patterns. It's is a gateway drug to functional programming. Try Elm after React when you're ready for your next FP step!

The "Bad"

Don't forget that React is mostly the view.

1. You DON'T GET any of the following:

  • An event system (other than vanilla DOM events)
  • Any AJAX capabilities whatsoever
  • Any form of a data layer
  • Promises
  • Any application framework

React on its own not enough for most real world use cases. This "bad" is actually a "good" in disguise. React has one job and does it well. But it certainly can be intimidating for beginners to dive in and work with data flow!

2. Welcome to Webpack and a new ecosystem

Webpack is a groundbreaking tool, but it's confusing. You're going to have to get to know it!

As Front End developers, we aren't used to applying static analysis, code compilation, and software engineering principles to our code. It's intimidating, but this "bad" is also a good. It's worth it in the end!

3. Flux and data flow are complex patterns for beginners

In the original React documentation, React and Flux were mentioned in the same breath, without much concern for a newcomer audience. It's gotten a lot better now, but since most people have graduated from Flux to Redux or other state management, understanding this data flow can still be difficult.

"Flux" in 10 seconds: Your view "dispatch"es an "action" (kind of like an event), like when a user types a name in a text field, that action tells your data store to update data, then the store triggers an event, and the view responds to that store's event by re-rendering with the latest data. Read more at "Flux for Beginners."

The main downside of Flux and other data patterns is that there's lots of them! There are many different "Flux" implementations.

As of 2017, Redux is the most popular state management library. If you want to learn it, I can't recommend the free Egghead.io online video course highly enough. It's by the Redux creator Dan Abramov and is one of the best tutorials I've been through.

Should I Use React?

Short answer: yes.

Long answer: probably, yes, for most things.

Here's why you should use React:

  • Works great for teams, strongly enforcing UI and workflow patterns
  • UI code is readable and maintainable
  • Componentized UI is the future of web development, and you need to start doing it now.

Here's why you should think twice before you switch:

  • React will slow you down at the start. Understanding how props, state, and component communication works is not straightforward, and the docs are a maze of information. This is countered by a speed up when your whole team is on board.
  • React does not support any browser below IE8.
  • If your application / website doesn't have very much dynamic page updating, you may be implementing a lot of code for a small benefit.
  • There's no one way to implement complex UI components (lightboxes, date pickers, etc). Finding the best libraries and patterns for your codebase will take some time.

That's It!

To learn more about Flux, check out the follow-up post, Flux For Beginners.

Make sure you don't walk away missing the point of JSX!

You're going to need to know Webpack. Try Webpack: When To Use and Why.

I hope this helped you understand React better. If it did, consider following me on Twitter.