So when I started out playing around with React I noticed it was a bit different from the way I normally approach coding in JavaScript. I’d like to go through some of the best practices that is going to make your life easier when building your first react apps.

1. JSX and the Virtual DOM in React

React is using JSX – a JavaScript syntax extension – that compiles to JavaScript and produces React elements that are added the DOM. Basically you can think of it as rendering HTML using JavaScript instead of firing up HTML-files, and even though JSX is optional in React it is highly recommended.

I thought it was the stupidest thing I’ve ever seen for about 15 minutes and then I absolutely fell in love with it due to its simplicity and that it basically is identical to HTML with some quirks (i.e. className and htmlFor). JSX must be put inside a component’s render function. Let’s take a look:

// Class component
class myComponent extends React.Component {
    render () { // using ES6 function shorthand () instead of function()
       return(<div className=”container”>Some text here.</div>);
    }
}

As you can see everything inside the parenthesis of the return block can be written like you normal html. What actually happens here is that JSX applies a façade design pattern (syntactic sugar) and compiles the code into JavaScript like this:

    React.createElement("div", { className: ”container” }, "Some text here.");

Also notice that we are using className instead of class, this is because class is a reserved word in JavaScript, this is one of a few quirks you need to get used to writing JSX.

2. Loading dependencies using ES6 modules

Prior to this experience I had worked a lot with frameworks such as Angular, Durandal and Dojo where Angular had something called dependency injection and the latter CommonJS and AMD (asynchronous module definition) or similar for loading dependencies.

The best practice for importing and exporting dependencies in React is using ES6 built-in modules. Here’s an example:

//------ myFunc.js ------
export default function () { ... };

//------ main1.js ------
import myFunc from 'myFunc';
myFunc();

So by using import and export you can organise your project into multiple files and load modules, classes, constants, data, third-party libraries etc in a flexible way.

This is important as your application grows and your code base is growing to improve readability. Isolating each part of your application also makes it easier to test.

3. One way data flow in React using props and state

Another best practice in react is the use of one-way data flow. This means that data changes come from the “top” of the app and are propagated “downwards” through its various components. To understand one way data flow (or unidirectional flow) one must understand props and state and how React renders.

Props is immutable data and is passed down from its parents – and is owned by the parent. If it needs to changed, the parent should just change its internal state. State on the other hand is mutable and owned by the component.

Setting the state using this.setState() will cause the app to re-render and should be minimised at all costs. This means that setting state should never be done inside the render function. One of the more challenging parts in React is determining what should be stateful and where state should live.

We want to handle state at the topmost component of our of app also called a “container” because when data has changed we have to feed our app and do the re-rendering to display a new version.

This may sound clumsy and non-performant for the newcomer but it is the opposite due to the comparison between the Virtual DOM and the actual DOM.

The beauty is that React will only touch elements that actually need to be changed – this is the magic (or passive DOM manipulation) that React provides and makes it fast compared to active DOM manipulation used in the past.

In more complex apps we connect with a store to handle state and thus applying the flux design pattern created by Facebook.

4. Use ECMAScript 6 features

There are several features in ES6 that can be used with React to boost efficiency – especially when things get a bit more complex and you need to copy enumerable properties from one object to another when handling state inside your store.

In general ES6 provides plenty of shorthand for i.e. functions that improves readability – it also goes very handy together with Typescript if you are already familiar with that.

Some of the most common ES6 features used in React are variable declaration using const and let, arrow functions, array map, destructuring, spread and rest operators, object assign, modules, classes, iterators and promises.

ES6 is not natively supported by all browsers yet so it is often combined using Babel with React to transpile into ES5.

Notice that all features are not supported with Babel out of the box (such as object assign) – you may require a library called babel-polyfill that can be pulled in as a dependency for your project.

Babel-polyfill should be used wisely in production as it is rather large in file size. A good practice is to only pull in the features that you are actually using in your code.

Let’s look at some examples

//------ Iterating through arrays containing objects using map

const products = [{name: "some product", id: 1}];
this.products.map((product) => {
   
<li key={product.id}>{product.name}</li>

});

//------ Spread operators can be passed in as arguments to a 
//------ component and will spread out all items in an array

const props = {firstName: 'Donald', lastName: 'Duck'};  
return <Greeting {...props} />;

//------ "Destructuring" can be used to create variables in child component
//------  when passed as props from a parent

var {name, id} = props;

5. Use Webpack

Webpack is a module bundler that is an extremely powerful tool and provides hot reloading, minification and bundling to make your life easier. If you are familiar with browserify, gulp or grunt I suggest reading this article to get some clarity on the topic.