React Best Practices and Useful Functions

Lately React has been becoming the new tool used by developers to create everything from a single page application to mobile applications. But since I started going deeper into React I have seen all this “cool” node modules that are extremely badly developed. They follow no rules, the components are way too big. They use state for pretty much everything, and they don’t leverage dumb components. Anyone with enough experience understands how much of a hassle this is to maintain and how much load it takes on the browser if you render every component every time. In this article I will walk you through React best practices, both on how to setup React and how to make it extremely fast.

Please note I will keep updating this article as new practices emerge.

Before you start reading please note React is a functional programming (FP) library. If you don’t know what FP is, please read this Stack Exchange response.

Use ES6 (transpiled with Babel)

ES6 will make your life a lot easier. It makes JS look and feel more modern. One great example with ES6 are Generators and Promises. Remember when there was a time that you had to do a bunch of nested calls to be able to do an asynchronous call. Well now I am glad to welcome you too Synchronous Asynchronous JS, (yea it’s as cool as it sounds). One great example of this are generators:

Where this:

Turns into this:

Use Webpack

The decision to use Webpack is simple: Hot reloading, minified files, node modules :), and you can split your applications into small pieces and lazy load them.

If you are planing on building a large scale applcation I recommend reading this article to understand how lazy loading works.

Use JSX

If you come from a web development background JSX will feel very natural. But if your background is not in web develop don’t worry too much, JSX is very easy to learn. Note that if don’t you don’t use JSX the application will be harder to maintain.

Always look at your bundle size

One tip to making your bundle way smaller is to import directly from the node module root path.

Do this:

import Foo from ‘foo/Foo’

instead of:

Import {Foo} from ‘foo’

Keep your components small (Very Small)

Rule of thumb is that if your render method has more than 10 lines is probably way too big. The whole idea of using React is code re-usability so if you just throw everything in one file you are losing the beauty of React.

What needs to have its own component?

When thinking React you need to think about code reusability and code structure. You would not create a component for a simple input element that only has one line of code. A component is a mix of “HTML” elements that the user perceives as one. I know that this sounds a little bit strange but lets see an example. Take a look at this login screen:

What is the structure behind it. You have a form that contains two inputs a button and a link. Lets see this in code:

Whats wrong here? Repetition. The inputs contain the same structure, why not make that a component.

Now that is beautiful. I will not get into much detail here but if you want to continue reading go to Thinking React.

What about State?

Best practice in React is to minimize your state. One thing to keep in mind is to avoid synchronizing state between a child and parent. In the above example we have a form in that form the state is passed down as a props from the view and every time the user updates the password and username the state is updated in the view and not the form.

Use ShouldComponentUpdate for performance optimization

React is a templating language that renders EVERY TIME the props or the state of the component changes. So imagine having to render the entire page every time there in an action. That takes a big load on the browser. That’s where ShouldComponentUpdate comes in, whenever React is rendering the view it checks to see if shouldComponentUpdate is returning false/true. So whenever you have a component that’s static do yourself a favor and return false. Or if is not static check to see if the props/state has changed.

If you want to read more on performance optimization read my article on React Perf

Think about inmutability

If you are coming from Scala or other high performance languages inmutability is a concept that you are probably really familiar with. But if you are not familiar with the concept think of immutability like having twins. They are very much alike and they look the same but they are not equal. For example:

What just happened? Object2 was created as a reference of object1 that means that in every sense of the word object2 is another way of referencing object1. When I created object3 I created a new object that has the same structure as object1. The Object.assign function takes a new object and then clones the structure of object1 therefore creating a new reference so when you compare object1 to object3 they are different. Why is this significant? Think of performance optimization, I mentioned above that React renders everytime the state of a component changes. When using the ShouldComponentUpdate function instead of doing a deep check to see if all the attributes are different you can simply compare the objects. If you want to know more keep reading this article.

Use Smart and Dumb Components

There is not much to say here other than you don’t need to have a state in every object. Ideally you will have a smart parent view and all the children are dumb components that just receive props and don’t have any logic in it. You can create a dumb component by doing something like this:

Dumb components are also easier to debug because it enforces the top down methodology that React is all about.

Use PropTypes

PropTypes help you set data validation for components. This is very useful when debugging and when working with multiple developers. Anyone working with a large team should read this article.

Always bind the functions in the constructor method

Whenever working with components that uses state try to bind components in the constructor method. Keep in mind that you can use ES7 now and you can bind the functions using something like this now (Instead of binding in the constructor):

someFunction = () => {
}

Use Redux/Flux

When dealing with data you want to use either Flux or Redux. Flux/Redux allows you to handle data easily and takes the pain away from handling front end cache. I personally use Redux because it forces you to have a more controlled file structure.

Keep in mind that sometimes it is very useful to use Redux/Flux but you might not need to keep the entire state of your application in one plain object. Read more about it here.

Use normalizr

Now that we are talking about data, I am going to take a moment and introduce you to the holy grail of dealing with complex data structures. Normalizr structures your nested json objects to simple structures that you can modify on the fly.

File structure

I am going to make a blunt statement here and say that I have only seen 2 file structures with React/Redux that makes things easy to work with.

First structure:

Second structure:

Use Containers (Depracated — 2017 Update Next Chapter)

The reason you want to use containers that pass down the data is because you want to avoid having to connect every view to a store when dealing with Flux/Redux. The best way to do this is to create two containers. One containing all secure views (views that need authentication) and one containing all insecure views. The best way to create a parent container is to clone the children and pass down the desired props.

Example:

Use Templates instead of Containers

While working with containers and cloning the props down to the views I found a more efficient way to do this. The way I recomend it now is instead of using containers is to create a BaseTemplate that is extended by an AuthenticatedTemplate and a NotAuthenticatedBaseTemplate. In does two templates you will add all the functionality and the state that is shared across all the none-authenticated/authenticated views. In the views instead of extending React.Component you extend the template. This way you avoid cloning any objects and you can filter the props that are send down the component tree.

Avoid Refs

Refs will only make your code harder to maintain. Plus when you use refs you are manipulating the virtual Dom directly. Which means that the component will have to re-render the whole Dom tree.

Use Prop validation

PropTypes will make your life a lot better when working with a large team. They allow you to seemly debug your components. They will also make your debugging a lot easier. In a way you are setting standard requirements for a specific component.

Other comments

I want to emphasize that that you should split all of your components into individual files.

Use a router: There is no much to say here other than if you want to create a single page app you need a router. I personally use React Router.

If you are using flux remember to unbind the store listening to change events. You don’t want to create memory leaks.

If you want to change the title of your application dynamically you can do something like this:

This repo is a great example of React/Redux authentication.

Whats new in 2017

Get ready for a major rewrite. The creators of react are now rebuilding reacts core. It has better performance, better animations, and more APIs you can leverage to build large applications. You can read more here.

Useful helper functions

The following function is an Object comparison function. Usage: check if state or props have change in shouldComponentUpdate

Create reducer dynamically

Usage:

Create constants:

Render if:

Usage: render component if somethingTrue

Change state value dynamically:

My webpack.config.js

Keep reading about React High Performance Applications here.

If you liked this article, please click that green 👏below so others can enjoy it. Also please ask questions or leave notes with any useful practices or useful functions you know.

Follow me on twitter @nesbtesh