The React best practices you need to follow in 2021

Nimisha Kapadia September 1, 2021

The React Best Practices to follow in 2021

Quick Summary: If you’re a front-end developer who creates very interactive user interfaces, you are most expected to get Reactjs in your toolkit. When working on your React-powered applications, you must be alert to tune with the React Best Practices. These practices will help to keep your code well organized.

ReactJS is an open-source JavaScript library. It used to build the user interface and the view layer of the Web Applications. Its ‘V’ in Model View Controller (MVC) architecture. Facebook launched React and actively maintained it. React allows developers to build complex UIs from a small and isolated code called “components.”

React contains two parts: components containing HTML code and an HTML document – where all your components will render. Here we will discuss a few React Best Practices you should follow in 2021 to keep your code in a well-organized manner.

 

Table of contents:

  1. Use functional components
  2. Keep your Components small and separate your functionalities
  3. Always name your React components.
  4. Use JavaScript destructuring to remove redundancy.
  5. Always prefer passing objects
  6. Use React developer tools
  7. Conditional rendering practices
  8. Use snippet libraries
  9. Use prop-types library
  10. Comment Code only where necessary
  11. Put CSS in JavaScript

 

1. Use functional components

A component is a JavaScript function or class with optional inputs i.e., properties(props) and returns a HTML via a render () function. Components in react are independent and reusable bits of code.

Components have Two types: a class component and a functional component.

Class components are simple classes that are stateful and have internal state and life cycle methods. Functional components are stateless. But by using react hooks, it can act as a stateful component. The functional components accept props as arguments and return React elements.

The advantages of functional components are :

  • Less code
  • Simpler compared to class-based functions
  • Stateless
  • No “this” binding
  • Easy to understand.
import React from 'react';
export default function App() {
return(
<h2>Hello world</h2>
);
}

 

2. Keep your Components small and separate your functionalities

React applications have a set of components. Developers create reusable UI components using React. When you write small components, you can easily read and understand the functionality of this component. It’s easier to update smaller components. The reusability of the code is also increased.

Function-specific standalone components make testing and maintenance easy. With smaller components, it’s easy to implement performance optimizations.

Each component is usually compact approx. 100–200 lines, which is easy for other developers to understand and modify the code.

When you write a code to do a couple of functions(activities) in a single component, it will be hard to understand and difficult to maintain.

For example, the App component contains two lists of Products and countries. The following code prints the whole products list and country list.

App.js

import React, { useState } from "react";
export default function App() {
  const [productList, setProductList] = useState([
    "product 1",
    "product 2",
    "product 3",
    "product 4",
  ]);

  const [countryList, setCountryList] = useState([
    "country 1",
    "country 2",
    "country 3",
    "country 4",
  ]);
 return( <div>
<ul>
       {productList.map( item=> {return<li>{item}</li> })
</ul>
<ul>

{countryList.map( item=> {
return<li>{item}</li>
})}

</ul>

</div>
 );
}

 
We can use the ItemsList component to display the product list and the countries. Therefore, the reusability of the code is increased, and clearly, functions(activities) are separated into two components.

App.js

import React, { useState } from "react";
import ItemsList from "./ItemsList";
export default function App() {
const [productList, setProductList] = useState([
     "product 1",
     "product 2",
     "product 3",
     "product 4",
]);

const [countryList, setCountryList]=useState([
	"country 1",
	"country 2",
	"country 3",
	"country 4"
	]);
 
  return(
	<div>
  	<ItemsList items={productList} />
  	<ItemsList items={countryList} />
	</div>
  );
}

ItemsList.js

function ItemsList(props){ return (
<ul>{props.items.map(item=>{
return
 	<li>{item}</li>
</ul>
})}

); }

 

3. Always name your React components.

// This is an unnamed component. Don’t do this

export default () => <div>...</div>

 
// This is a named component

export default function Products () { return <div>...</div> )

 

Naming Convention for react component

There are three naming conventions in React.

  •  The component name should be Pascal Case – Which translates to names without spaces and capitalizing the first letter of every word. For example, UserInfo, ExpenseItem, etc.
  •  Elements that need keys should be unique (individual students or entries in a StudentInfo or List). Do not Use indexes for keys. You can have a key assignment made of a concatenation of two different object properties.The essential purpose of the key is to store basic information so that React can get a sense of what has changed in the application.
  • Method names should be in camelCase and named based on their functionality. Method names should be not application specific but for their purpose in the application – for example, submitForm, updateData, etc.

 

4. Use JavaScript destructuring to remove redundancy.

De-structuring is a JavaScript feature; it separates multiple data sections from an array or object and assigns them to their new variables created by the developers.

These new variables can be used later on in a React component.

Arguments can be passed as props from parent to child components. For example, in the following code, the Parent component (App) sends its state values to the child (Total) component as a prop. Here, props. Values are redundant four times.

App.js

import React from "react";
export default class App extends React.Component {
  state = { value1: 2, value2: 5, value3: 6, value4: 8 };

  render() {
    return <Total values={this.state} />;
  }
}

function Total(props) {
  return (
    <h2>
      sum:{" "}
      {props.values.value1 +
        props.values.value2 +
        props.values.value3 +
        props.values.value4}
    </h2>
  );
}

   
We can use JavaScript destructuring feature to remove redundancy of props.values.b by writing:

const {value 1, value 2, value 3, value 4} = props.values;

Function Total(props){
   const {value 1, value 2, value 3, value 4} = props.values;
   Return <h2> Total: { value 1 + value 2 + value 3 + value 4 } </h2>;
}

   

5. Always prefer passing objects

Passing an object instead of passing a set of primitive values is one of the good ways to limit the number of props passed. For example, instead of passing each detail of a Student, you can group them. If the student gains extra data down the road, this function won’t be modified to accommodate that.

// Don't pass primitives

<StudentAccount
     name={user.name}
     email={user.email}
     id={user.id}
/>

// Pass objects
<StudentAccount user={user} />

  

6. Use React developer tools

When you develop a React project, React developer tools are handy. It understands the component hierarchy, props, and children, component’s state, and it also helps to debug the code.

React developer tools help developers to create interactive UIs smoothly.

The React Developer tool is constantly updated with new features. It is a necessary instrument you can use to inspect a React application.

  

7. Conditional rendering practices

There are many better ways to do conditional rendering. Short circuit operators are a very short and simple way to perform conditional rendering:

// Short circuit operator

const Total= ({total}) => {
return <div>
{total && <h1>Total: {total}</h1>}
</div>
}

 

8. Use snippet libraries

Always try to use the best and most recent syntax to write your code. Code snippets help you to make your syntax updated. They also help to keep your code bug-free. So using code snippet libraries is one of the React Best practices that you need to follow. Snippet libraries like ES7 React, Redux, JS Snippets, etc., can be used.
 

9. Use prop-types library

PropTypes is React’s mechanism to confirm that components use the right data type and pass the correct data. propTypes property is used to set up type checking for React components.

Prop-types are a library for type checking props. It helps to prevent bugs when passing the wrong data-type props to a component.

import PropTypes from 'prop-types';

function DisplayName(props) {
return(
<h2>{props.name}</h2> ); 
}

DisplayName.propTypes = {
name: PropTypes.string.isRequired
}

 

10. Comment Code only where necessary

Write comments in code where it is necessary. It is one of the ways to follow best practices. By doing this, it serves two purposes simultaneously.

  • It will keep the code mess-free.
  • You can avoid possible conflict between code and comment if you have a chance to change the code at some time later.

 

11. Code should execute as expected and be easily testable

There is no explanation required for this rule. The code written by the developer needs to work as expected, and it can be testable quickly and smoothly. It is a good practice to give a name to your test file similar to the source file with a .test suffix. So, you can easily find the test files in the project. Developers can use JEST to test their React Code.
 

12. Follow linting rules, break up long lines.

Linting is a process in which we run a program that analyses code for possible errors.

Generally, we use the linting process for language-related issues. But it can also fix many other problems automatically, particularly code style. When you use a linter in your react code, it will help to keep your code relatively error-free and bug-free.
 

13. Put CSS in JavaScript

It is a standard practice to have all the CSS styles in a single SCSS file in your working project. The use of a global prefix avoids any possible name crashes. Yet, when your project scales up, this solution may not be reasonable.

There are several libraries offered that enable you to write down CSS in JavaScript. EmotionJS and Glamorous are the two most well-liked CSS in JS libraries.

EmotionJS will create complete CSS files for your production. Here is an example of using EmotionJS.

First, install EmotionJS using npm.

npm install --save @emotion/core

 
Second step, import EmotionJS in your React application.

import { jsx } from '@emotion/core'

 
Now, you can set the properties of an element as shown in the snippet below:

let Component = props => {

return ( <div
css= {{ border: '1px' }}
{...props}
/> )
}

 
 

Conclusion

I hope these React best practices will help you put your projects on the right track and improve your code, coding skills, and application performance.

Hire React Developers

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments