7 myths about React

7-myths-about-react-header.png

React, despite its widespread use in the front-end development scene today, is a very misunderstood tool. It is a library for building user interfaces, originally developed at Facebook, but is now being used by thousands of other companies such as Twitter, Dropbox, Paypal and more. To illustrate just how popular React has become, the core \[…\]

Introduction

React, despite its widespread use in the front-end development scene today, is a very misunderstood tool.

It is a library for building user interfaces, originally developed at Facebook, but is now being used by thousands of other companies such as Twitter, Dropbox, Paypal and more.

To illustrate just how popular React has become, the core library was downloaded almost 7 million times in the month of October 2017 alone, and it now has over 80,000 stars on GitHub at the time of writing this article.

For a library as popular as React, it is not surprising that a lot of misconceptions often crop up when participating in discussions concerning the use of the library.

In this article, I will address seven myths often held when it comes to React.

React is a framework

There is a common misconception that React is a fully fledged framework, similar to monolithic frameworks such as Angular or Ember, but this is not the case.

Although React is often used to describe the entire stack of supporting libraries for its ecosystem, the core library is only concerned with how the view layer of an application is handled which makes it really easy to introduce it into a project.

Most frameworks have strong opinions about how your project should be structured and organized, but this is not the case with React. It is much more flexible and modular which makes it more adaptable to a wide range of projects.

A fairly experienced developer should be able to learn enough React in less than a day to become productive with it at once. This is not the case with most frameworks.

JSX is required to use React

JavaScript Syntax Extension (JSX) was popularized by React as a way of defining the UI of an application. The syntax looks like HTML but it comes with the full power of JavaScript which makes it easy to reason about what a specific component renders.

Some people are put off from using React because they feel including an HTML-like syntax into JavaScript code violates separation of concerns principle, but this is misguided reasoning since JSX isn’t HTML and is indeed compiled down to regular JavaScript code using transpilers such as Babel.

In any case, JSX is not a hard requirement for using React. You can choose to use a template language such as React Templates or skip templates altogether and use React.createElement() directly. JSX is actually just syntactic sugar for the React.createElement() function.

For example, this code written with JSX:

1class HelloWorld extends React.Component {
2      render() {
3        return <h1>Hello world</h1>
4      }
5    }

will be compiled down to the following using Babel:

1class HelloWorld extends React.Component {
2      render() {
3        return React.createElement(
4          "h1",
5          null,
6          "Hello world"
7        );
8      }
9    }

Realistically speaking, embracing React almost certainly means embracing JSX since the creators of React advocate for its use and the vast majority of tutorials and supporting libraries for React assume the use of JSX.

But, if you really dislike JSX, you are free to simply not use it in your application.

React is faster than the DOM

Under the hood, React uses what is popularly referred to as the “Virtual DOM” which is basically a tree of JavaScript objects that represents the actual browser DOM.

This is why, when writing React apps, you do not manipulate the DOM directly, jQuery-style. Rather, you’ll tell React how you want the DOM to look like by manipulating the state object, and allow React make the appropriate updates to the browser DOM.

This creates a comprehensible development model for developers because you don’t have to keep track of all DOM state changes. Instead, you simply modify the state object and React uses efficient diffing algorithms in order to know what part of the UI changed compared to the previous DOM representation, and uses that information to update the actual browser DOM.

The major benefit of this Virtual DOM approach is that it provides a nice API for creating UI, and minimizes the amount of updates to be made to the browser DOM, but it cannot be faster than carefully crafted manual DOM updates.

This is because, by definition, it has to do some extra work figuring out what parts of the UI needs to be updated before going ahead to perform the updates. So, although the Virtual DOM approach brings a lot of good things to the table, insane levels of speed is not one of them.

If you update the DOM yourself with vanilla JavaScript, nothing else can beat it in terms of performance. React is, nonetheless, fast enough for most practical uses cases and provides lovely ergonomics for developers which is why it has been widely adopted in the JavaScript ecosystem.

ES6 is required to write React

If you have not yet started taking advantage of the newer features and syntax introduced in ES6 (ES2015), it is still very possible to adopt React into your technology stack using a purely ES5 approach.

React provides the create-react-class module as a substitute for fleshing out components instead of using the class syntax.

You can install it by running:

1npm install create-react-class --save

And then used it in your code like this:

1var createReactClass = require('create-react-class');
2    var sayHello = createReactClass({
3      render: function() {
4        return <h1>Hello from out app</h1>;
5      }
6    });

Although the community has largely embraced the ES6 class declaration syntax, both approaches produce a React component with the same capabilities.

Before you adopt this method, keep in mind that the API of the ES6 class declaration method is not strictly compatible with the create-react-class approach.

For example, with ES6 classes, methods of the component are not bound to the instance automatically. You have to explicitly bind it either by setting it in the class constructor

1class Greeting extends React.Component {
2      constructor(props) {
3        super(props);
4        this.state = {
5            count: 0
6        }
7        // bind methods here
8        this.handleClick = this.handleClick.bind(this);
9      }
10
11      handleClick() {
12        this.setState({
13            count: this.state.count + 1
14        });
15      }
16
17      render() {
18        return (
19              <button onClick={this.handleClick}>Click Me</button>
20        );
21      }
22    }

Or by binding it inline in the JSX:

1class Greeting extends React.Component {
2      constructor(props) {
3        super(props);
4        this.state = {
5            count: 0
6        }
7      }
8
9      handleClick() {
10        this.setState({
11            count: this.state.count + 1
12        });
13      }
14
15      render() {
16        return (
17              <button onClick={this.handleClick.bind(this)}>Click Me</button>
18        );
19      }
20    }

When using create-react-class, you don’t have to worry about this since it binds all methods to the instance of the component automatically.

You can find out about the other differences between the two approaches in the relevant documentation.

React applications are complicated to setup

React applications used to be very complicated to setup. You needed to have a lot of things in place before you can start building your app. This typically included some form of compilation step that involved setting up build tools such as Webpack, Browserify, Gulp, Babel and the likes, a very tedious process indeed!

However, since Create React App was introduced by the React team, this is no longer the case. It helps you bootstrap a single page React application in a few seconds with no configuration required and even optimizes your application for production.

Although create-react-app uses tools like Webpack, ESLint, and Babel under the hood, these are already configured for you and hidden away so you can focus on writing the code for your application.

You can install it by running the following command in your terminal:

1npm install -g create-react-app

Following that, creating a React application is as easy as running the command below, where HelloWorld is the name of your application.

1create-react-app HelloWorld

Once all the dependencies for your app have been installed, you can change to it’s directory and run npm start to launch the app in development mode. Then preview it in your browser by navigating to http://localhost:3000.

If, during your development cycle, the configuration provided by create-react-app does not meet your needs anymore, you can easily ditch it by “ejecting” to a custom setup. By running npm run eject, all the configuration files and dependencies are copied right into your project so you can customize them however you like.

You need to use Redux with React

State management is a common concern for developers when building Single Page Applications. This is because you’ll typically be juggling a lot of state between components and it can get unwieldy for complex applications.

Redux was designed to solve the problem of state management by helping to keep state centralized so that we have a “single source of truth” in the application, instead of requiring that each component manage its own state.

Often, people lump React and Redux together as if one cannot be used without the other, but this is not so. While Redux is most commonly used in the React ecosystem, it can be used with any other view library.

And you can definitely use React without Redux by learning how to manage local state in React and the different techniques you can use to scale your local state management.

You may later adopt Redux, or any other library that implements the Flux architecture, into your workflow if the local way of managing state does not scale well for your particular needs.

You must use inline styles with React

One of React’s core ideas is to decompose the UI of an application into different, self-contained pieces called components which are meant to be reusable.

This encourages putting the markup, logic and styling for a component in the same context since you can’t have a self-contained component if its styles are defined in a separate location.

For this reason, React favors an inline approach for styling components:

1const divStyle = {
2      color: 'blue',
3      fontSize: '15px',
4    };
5
6    const HelloWorldComponent = () => <div style={divStyle}>Hello World!</div>;

This involves defining the styles for a component in a JavaScript object whose keys are the camelCased version of the corresponding CSS property. Then you apply the style to an element by setting its style attribute to refer to that object.

If you view the rendered output in your browser’s developer tools, you will see that the styles are indeed rendered inline.

While this method deviates significantly from the conventional “best practice” in web development which advocates for separating logic from presentation, it opens the door to many interesting solutions to common CSS problems.

If you do not want to adopt this system, you will be glad to hear that there are a number of alternative approaches when it comes to styling React components.

You can write CSS the traditional way, that is, inside regular CSS files, and import each file into its corresponding component, or you can use your favourite preprocessor to compile the stylesheets depending on your build system. This is the approach used by default in Create React App.

1import React, { Component } from 'react';
2    import './Clock.css';
3
4    class Clock extends React.Component {
5    // ...
6    }
7
8    export default Clock;

You can also adopt one of the several CSS-In-JS libraries which allows you to use component-level styles in your application that are written with a mixture of JavaScript and CSS.

Wrap Up

I hope this article has helped you discover the truth about React, what it brings to the table, and why you should consider adopting it on your next project. If you have any feedback or questions regarding this topic, feel free to leave a comment below.