Tutorials Books Videos Forums

Change the theme! Search!
Rambo ftw!

Customize Theme


Color

Background


Done

Table of Contents

Introducing React

by kirupa   |   filed under Learning React

Ignoring for a moment that web apps today both look and feel nicer than what they did back in the day, there is something even more fundamental that has changed. The way we architect and build web apps is very different now. To highlight this, let's take a look at the following app:

This app is a simple catalog browser for something. Like any app of this sort, you have your usual set of pages revolving around a home page, a search results page, a details page, and so on.

Old School Multi-Page Design

If you had to build this app a few years ago, you would have taken an approach that involved multiple, individual pages. The flow would have looked something like this:

For almost every action that changes what the browser displays, the web app will navigate you to a whole different page. This is a big deal beyond just the less-than-stellar user experience that users will see as pages get torn down and redrawn. This has a big impact on how you maintain your app state. Outside of storing some user data via cookies and some server-side mechanism, you simply don't need to care. Life is good.

New School Single-Page Apps

Today, going with a web app model that requires navigating between individual pages seems dated...like, really dated:

Instead, modern apps tend to adhere to what is known as a Single-page App (SPA) model. This is a world where you never navigate to different pages or ever even reload a page. Instead, the different views of your app are loaded and unloaded into the same page itself.

For our app, this may look something like this:

As users interact with our app, we replace the contents of the dotted red region with the data and HTML that matches what the user is trying to do. The end result is a much more fluid experience. You can even use a lot of visual techniques to have your new content transition in nicely just like you might see in cool apps on your mobile device or desktop. This sort of stuff is simply not possible when navigating to different pages.

All of this may sound a bit crazy if you've never heard of single-page apps before, but there is a very good chance you've run into some of them in the wild. If you've ever used popular web apps like Gmail, Facebook, Instagram, or Twitter, you were essentially using a single-page app. In all those apps, the content gets dynamically displayed without requiring you to refresh or navigate to a different page!

Now, I am making these single page apps seem really complicated. That's not entirely the case. Thanks to a lot of great improvements in both JavaScript and a variety of 3rd party frameworks and libraries, building single page apps has never been easier. That doesn't mean there is no room for improvement, though.

When building single-page apps, there are three major issues that you'll encounter at some point:

  1. In a single page application, the bulk of your time will be spent keeping your data in-sync with your UI. For example, if a user loads new content, do we explicitly clear out the search field? Do we keep the active tab on a navigation element still visible? Which elements do we keep on the page, and which do we destroy?

These are all problems unique to single-page apps. When navigating between pages in the old model, we just assumed everything in our UI would be destroyed and just built back up again. This was never a problem.

  1. Manipulating the DOM is really REALLY slow. Manually querying elements, adding children, removing subtrees, and performing other DOM operations is one of the slowest things you can do in your browser. Unfortunately, in a single page app, you'll be doing a lot of this. Manipulating the DOM is the primary way you are able to react to user actions and display new content.
  2. Working with HTML templates can be a pain. Navigation in a single-page app is nothing more than you dealing with fragments of HTML to represent whatever it is you wish to display. These fragments of HTML are often known as templates, and using JavaScript to manipulate them and fill them out with data gets really complicated really quickly.

To make things worse, depending on the framework you are using, the way your templates look and interact with data can vary wildly. For example, this is what a template in Mustache looks like:

var view = {
  title: "Joe",
  calc: function () {
    return 2 + 4;
  }
};

var output = Mustache.render("{{title}} spends {{calc}}", view);

Sometimes, your templates may look like some clean HTML that you can proudly show off in front of the class. Other times, your templates might be unintelligible with a boatload custom tags designed to help map your HTML elements to some data.

Despite some of these shortcomings, single page apps aren't going anywhere. They are a part of the present, and they will fully form the future of how web apps are built. That doesn't mean that we have to tolerate these shortcomings. To address this...

OMG! A React Book Written by Kirupa?!!

To kick your React skills up a few notches, everything you see here and more (with all its casual clarity!) is available in both paperback and digital editions.

BUY ON AMAZON

Meet React

Facebook (and Instagram) decided that enough is enough. Given their boatload of experience with single-page apps, they released a library called React to not only address these shortcomings, but to also change how we think about building single-page apps:

In the following sections, let's look at the big things React brings to the table.

Automatic UI State Management

With single-page apps, keeping track of your UI and maintaining state is hard...and very time-consuming. With React, you need to worry only about one thing: the final state your UI is in. It doesn't matter what state your UI started out in. It doesn't matter what series of steps our users may have taken to change the UI. All that matters is where your UI ended up:

React takes care of everything else. It figures out what needs to happen to ensure your UI is represented properly, so all of that state management stuff is no longer your concern.

Lightning-fast DOM Manipulation

Because DOM modifications are really slow, you never modify the DOM directly using React. Instead, you modify an in-memory virtual DOM instead:

Manipulating this virtual DOM is extremely fast, and React takes care of updating the real DOM when the time is right. It does so by comparing the changes between your virtual DOM and the real DOM, figuring out which changes actually matter, and making the least amount of DOM changes needed to keep everything up-to-date in a process called reconciliation.

APIs to Create Truly Composable UIs

Instead of treating the visual elements in your app as one monolithic chunk, React encourages you to break your visual elements into smaller and smaller components:

Just like everything else in programming, it is a good idea to have things be modular, compact, and self-contained. React extends that well-worn idea to how we should think about user interfaces as well. Many of React's core APIs revolve around making it easier to create smaller visual components that can later be composed with other visual components to make larger and more complex visual components...kinda like Russian Matroshka dolls:

This is one of the major ways React simplifies (and changes) how we think about building the visuals for our web apps.

Visuals Defined Entirely in JavaScript

While this sounds ridiculously crazy and outrageous, hear me out. Besides a really weird syntax, HTML templates traditionally suffered from another major problem. You are limited in the variety of things you can do inside them that goes beyond simply displaying data. If you wanted to choose which piece of UI to display based on a particular condition, for example, you had to write JavaScript somewhere else in your app or use some weird framework-specific templating command to make it work.

For example, here is what a conditional statement inside an EmberJS template looks like:

{{#if person}}
  Welcome back, {{person.firstName}} {{person.lastName}}!
{{else}}
  Please log in.
{{/if}}

What React does is pretty neat. By having your UI defined entirely in JavaScript, you get to use all of the rich functionality JavaScript provides for doing all sorts of things inside your templates. You are limited only by what JavaScript supports as opposed to any limitations imposed by your templating framework.

Now, when you think of visuals defined entirely in JavaScript, you are probably thinking something horrible involving quotation marks, escape characters, and a whole lot of createElement calls. Don't worry. React allows you to (optionally) specify your visuals using an HTML-like syntax known as JSX that lives fully alongside your JavaScript. Instead of writing code to define your UI, you are basically specifying markup:

ReactDOM.render(
  <div>
    <h1>Batman</h1>
    <h1>Iron Man</h1>
    <h1>Nicolas Cage</h1>
    <h1>Mega Man</h1>
  </div>,
  destination
);

This same code defined in JavaScript would look like this:

ReactDOM.render(React.createElement(
  "div",
  null,
  React.createElement(
    "h1",
    null,
    "Batman"
  ),
  React.createElement(
    "h1",
    null,
    "Iron Man"
  ),
  React.createElement(
    "h1",
    null,
    "Nicolas Cage"
  ),
  React.createElement(
    "h1",
    null,
    "Mega Man"
  )
), destination);

Yikes! By using JSX, you are able to define your visuals very easily using a syntax that is very familiar, while still getting all the power and flexibility that JavaScript provides. Best of all, in React, your visuals and JavaScript often live in the same location. You no longer have to jump between multiple files to define the look and behavior of one visual component. This is templating done right.

Just the V in an MVC Architecture

We are almost done here! React is not a full-fledged framework that has an opinion on how everything in your app should behave. Instead, React works primarily in the View layer where all of its worries and concerns revolve around your visual elements and keeping them up-to-date. This means you are free to use whatever you want for the M and C part of your MVC architecture. This flexibility allows you to pick and choose what technologies you are familiar with, and this makes React useful not only for new web apps you create, but also for existing apps you'd like to enhance without removing and refactoring a whole bunch of code.

Conclusion

As new web frameworks and libraries go, React is quite the runaway success. It not only dealt with the most common problems developers faced when building single-page apps, it threw in a few additional tricks that make building the visuals for your single-page apps much MUCH easier. Since it came out in 2013, React has also steadily found its way into popular web sites and apps that you probably use. Besides Facebook and Instagram, some of the notable ones include the BBC, Khan Academy, PayPal, Reddit, The New York Times, Yahoo, and many more.

This article was an introduction to what React does and why it does it. In future tutorials, we'll dive deeper into everything you've seen here and cover the technical details that will help you successfully use React in your own projects. Stick around.

Next tutorial: Building Your First React App

Just a final word before we wrap up. If you have a question and/or want to be part of a friendly, collaborative community of over 220k other developers like yourself, post on the forums for a quick response!

Kirupa's signature!

The KIRUPA Newsletter

Thought provoking content that lives at the intersection of design 🎨, development 🤖, and business 💰 - delivered weekly to over a bazillion subscribers!

SUBSCRIBE NOW

Creating engaging and entertaining content for designers and developers since 1998.

Follow:

Popular

Loose Ends

:: Copyright KIRUPA 2024 //--