The Nine Most Important React and Web Development Best Practices

Carlos Santana
The Mindbody Dev Report
5 min readFeb 28, 2019

NOTE: This article assumes you have some experience in React, JavaScript and Web Development topics.

My name is Carlos Santana, I’m a Senior React Developer at Mindbody and author of the book React Cookbook (Packt Editorial).

React is a very popular framework, and hundreds of new packages are created every week. Unfortunately, doing simple tasks in React can be complicated, and there’s very little documentation about good practices. This article lays out some best practices and offers tips to improve and speed up your React codebase.

1: Add the Component’s Name in the First Wrapper of Each Component

It’s easier to find a component when debugging your code using the React Dev Tools if you’ve included the component’s name at the beginning of a class name.

NOTE: You should install React Dev Tools for Chrome if you haven’t already.

For example:

const AutomationCard = props => {
return (
<div className="platy-automations__card">
...
</div>
);
};

Will be:

const AutomationCard = props => {
return (
<div className="AutomationCard platy-automations__card">
...
</div>
);
};

2: Use CSS Modules

If you have ever styled a component and realized that unwanted CSS is being applied, you probably tried one of two things: changing the class name or using the !important rule. Well, there is a third and more efficient way to solve this issue through CSS Modules.

A CSS Module is a CSS file in which all classes and animation names are scoped locally by default in order to isolate styles, making your CSS modular and reusable. By removing conflicts and global scope, explicit dependencies and BEM will not be needed anymore.

To enable CSS Modules, you can add the configuration below in Webpack. In order to isolate the styles, it will add a unique suffix with a random hash to all class names.

{
loader: "css-loader",
options: {
sourceMap: true,
modules: true,
localIdentName: "[local]___[hash:base64:5]" // Right here
}
}

3: Add Git Hooks for Linting and Testing

You probably already have a linting and testing process running on a CI platform. The main issue is that developers often forget to validate their code before creating a commit or pushing changes. As a result, we waste time waiting for the build to finish in the CI tool just to find out if there’s any linting violations or test failures.

To save some time, you can add git hooks in your git-flow to execute the linter or the tests. For example, you can specify that your linter runs on “pre-commit,” or have your tests run on a “pre-push”. This way you can identify failing tests or code linting violations without pushing your changes up and having to wait for the CI build to fail.

In order to implement those git hooks, we can use husky and add this in our package.json file.

{
"husky": {
"hooks": {
"pre-commit": "npm run lint",
"pre-push": "npm test"
}
}
}

You can always skip the git hooks with two commands:

  • To skip pre-commit:
git commit -nm "The message of your commit"
  • To skip pre-push:
git push origin <your-feature-branch> --no-verify

4: Take Advantage of Destructuring

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays (or properties from objects) into distinct variables.

In React there are three popular ways of destructuring:

Destructuring prop-types on the import:

import { array, bool, object, string } from 'prop-types';

Destructuring props (objects):

const { myFirstProp, mySecondProp } = this.props;
const { my_location_prop: myLocationProp } = this.props;

Destructuring arrays:

const [filename, extension] = value.split('.'); // myFile.png

5: Use Clean Redux Containers (without JSX)

Another trick is to remove all JSX code from your React containers. To do that, just bind the actions to Redux, specify the Redux states, then connect a wrapper component to inject all the props.

This will give you clean containers, making testing easier, and improve your webpage performance by removing an extra React component with all the lifecycle methods.

Here’s an example of a clean container:

// Dependencies
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
// Components
import Layout from '../components/Layout';
// Actions
import { fetchPosts } from '../actions';
import { getComments } from '../../comments/actions';
export default connect(({ blog, comments }) => ({
posts: blog.posts,
comments: comments.list
}), dispatch => bindActionCreators({
fetchPosts,
getComments
}, dispatch))(Layout);

6: Use shouldComponentUpdate to Reduce the Unnecessary Renders

Use shouldComponentUpdate() to let React know if a component’s output is not affected by the current change in state or props. The default behavior is to re-render on every state change, and in the vast majority of cases, you should rely on the default behavior.

You can invoke shouldComponentUpdate() before rendering when new props or states are being received and return a boolean value. If it’s true then the component will re-render, and if it’s false then the re-render will be skipped.

Be careful when using this function to not affect the component’s functionality. By default, this method returns true in all class components.

Knowing when to use shouldComponentUpdate vs. when to use a Pure component can be confusing. The Pure components normally are useful if your components are “pure”, meaning they always render the same result for the same inputs. Also, Pure components do not have the shouldComponentUpdate method.

On the other hand, shouldComponentUpdate is helpful when we have heavy components that execute a lot of extra renders. In this case, we can limit the number of renders by adding a conditional, but in any circumstances, Pure components will replace the shouldComponentUpdate.

I go into more detail on the use of Pure Components on my personal blog (Dev Education).

7: Upgrade to Webpack 4.x

Webpack to 4.x will make webpack 98% faster and significantly reduce the build times. See this article for more details on what changed.

8: Rename .js to .jsx Extension for Files Containing JSX Code

Rename your file extensions that contain jsx to .jsx instead of .js. You can enable this ESLint rule to check whether a file contains JSX without opening the file.

This rule is good if you like to be organized and strict with your standards.

9: Avoid Importing the Entire Lodash Library

A common mistake when using lodash on your website is importing the entire lodash library without knowing it. This will cause your bundle to be huge since lodash is 527kb uncompressed.

Instead, import the specific functionality that you need from the specific file that it’s in. For example, instead of adding:

// This will import the entire library
import { map } from 'lodash';

You can do:

// This will just import the map function
import map from 'lodash/map';

This will import just ~10kb instead of the entire lodash package.

I hope that these tips and tricks for React will help you to improve your codebase. You can also find more tips in my book: React Cookbook.

--

--