React Best Practices To Follow In 2021

  Solace  Infotech    May 20, 2021    379

 

React is a well known open-source JavaScript library that is used to create unique and innovative applications. It was created by Facebook and allows integration with many exciting components, libraries and frameworks. Also, developers can make their own components. Developing an app with React is not as simple as it looks. Knowing the react best practices will help you to develop an effective app within less time. Still, if you are not aware of the react best practices, then this blog is for you. Let us see the React best practices.

Know the reasons to use React for app development at- Why you should build your app with react native?

React Best Practices To Follow In 2021-

1. Project Structure-

1.1 Folder layout-

Architecture mainly focuses on reusable components of react developer architecture so as to share the design pattern among multiple internal projects. So the component-centric file structure should be used that means all the files related to a different component (Javascript, assets, CSS etc.) should be kept under a single folder. 

Components
	|
	--Login
		|
		--tests--
		--Login.test.js
		--Login.jsx
		--Login.scss
		--LoginAPI.js

This one is another approach used in grouping the file types. In this, the same type of files is kept under one folder. Here, same type of files is kept under one folder. For instance,

APIs
  |	
  --LoginAPI
  --ProfileAPI
  --UserAPI

Components
  |	 
  --Login.jsx
  --Login.test.js
  --Profile.jsx
  --Profile.test.js
  --User.jsx

Above structure is the basic example. The folders can be further nested based on requirements.

1.2 Css in JS-

In huge projects, theming and styling can be challenging tasks like maintaining nig scss files. Hence, the concept of CSS-in-JS solutions comes into focus. Following libraries are based on it-

  • EmotionJS
  • Styled Components
  • Glamorous

Among those libraries, you can use as per your requirement such as, for complicated themes, you can select styled-components or Glamorous.

2. Coding Style Best Practices-

2.1 Naming Conventions-

When you work with React, generally you are using JSX(Javascript extensions) files. A component that you create for React should be named in Pascal case, or upper camel case. This translates to names without spaces and capitalizing the first letter of every word. If you have to create a function that submits a form, you should name it SubmitForm in upper camel case, instead of SubmitFormsubmit_form. Generally, Upper camel case is called the Pascal case.

For globally used Constant fields in the application, try to use only capital letters. For example, PI = “3.14”;

2.2 Avoid unnecessary DIV-

When there is a single component to be returned, no need to use <div>.

return (
   <div>
   <Button>Close</Button>
   </div>
);

Whenever there are multiple components to be returned, use in shorthand form <> as below-

return (
 <Button>Close</Button>
);

2.3 Consolidate duplicate code – DRY your code-

For all code, common rule is to keep it as brief and concise as possible. One way to do this is to avoid duplication- Don’t Repeat Yourself(DRY). One can do this by scrutinizing the code for patterns and similarities. If you find any, it is possible you’re repeating code and there’s scope to remove duplication. Mostly, rewriting can make it more concise. It highly depends on the reusability principle in React.

For instance, you have to add multiple buttons that includes icons, rather than adding markup for each button, you just need to use IconButton component. You could go further by mapping everything into an array.

const buttons = ['facebook', 'twitter', 'youtube'];
return (
  <div>
    {
      buttons.map( (button) => {
        return (
          <IconButton
            onClick={doStuff( button )}
            iconClass={button}
          />
        );
      } )
    }
  </div>
);

2.4 Apply ES6 Spread Function-

It will be an easy and productive way to use ES6 functions to pass an object property. By using {…props} between open and close tag will automatically add all props of object.

 

let propertiesList = {
  className: "my-favorite-props ",
  id: "myFav",
  content: "Hello my favourite!"
};
let SmallDiv = props => <div {... props} />;
let mainDiv = < SmallDiv props={propertiesList} />;

You can make use of spread function:

  • There is need to pass just HTML tag attributes and content
  • There is no need of ternary operators.

For the repetitive use of functions, don’t use spread function when, 

  • There are dynamic properties
  • Need for array or object properties
  • In case of render where nested tags are necessary 

2.5 Write Tests for each component-

It is better to write test cases for each component developed because it reduces the chances of errors when code is deployed. You can check all possible scenarios in unit testing. Jest or enzymes are mostly used react test frameworks.

2.6 Code should execute as expected and be testable-

Code that you write should behave as expected and be quickly and easily testable. It is good to name your test files identical to source files with .test suffix. Then it’ll be easy to find test files. You can use JEST to test react code.

3. React Component Best Practices-

3.1 Divide into small components-

Divide large components into small components like each component performs one function as much as possible. It becomes easy to manage, test and reuse small components.

3.2 Appropriate Naming and Destructuring Props-

To keep clean and readable code, use meaningful and short names for component props. Use props destructing feature of function that discards the need to write props with each property name and can be used as it is.

const funcDestruct = ({name, title}) => {
return (
<div>
<p>{name} – {title}</p>
</div>
)
}

With props destructing, you can directly use name and title without using props.name or props.title.

3.3 Use Functional or Class Components based on Requirement-

If you’ve to show User Interfaces without implementing any logic or state change, use functional components in place of class components as functional components are efficient here. For instance-

// class component
class Cat extends React.Component {
  render () {
	let { badOrGood, type, color } = this.props;
	return <div classname="{type}">My {color} cat is { badOrGood } </div>;
  }
}
 
Vs.
 
//function component
 
let Cat = (badOrGood, type, color) => <div classname="{type}">My {color} cat is { badOrGood }</div>;
  • When using functional components, you lose control over the render process. Means with small change in components, the functional component always re-renders.
  • React lifecycle methods such as componentDidMount()componentDidUpdate() etc. cannot be used with functional components, but can be used with Class components.

3.4 Use propTypes for Type Checking and preventing errors-

It is better to do type checking for props passes to a component that can help to prevent bugs. Let us see how to use-

React.PropTypes:

import React, { Component } from “react”;
import PropTypes from “prop-types”;
class PropTypeExample extends Component {
 render() {
 const { username } = this.props;
 return
<h1>Welcome, { username }</h1>
 }
}
PropTypeExample.PropTypes = {
 name: PropTypes.string.isRequired
};

4. ReactJS Security Best Practices-

4.1. HTTP Authentication-

Authentication should be secure as the client-side authentication and authorization can be exposed to many security defects that may destroy the protocols in application. Most commonly used technique for adding authenticity can be validated using AuthO, React Router, OAuth, JSON Web Token(JWT), PassportJs

Security with JWT-

  • Try not to keep JWT tokens based on Local Storage. As it would be simple for anyone to get a token using the browser’s Dev tools console and write.  console.log(localStorage.getItem(‘token’))
  • Keep you tokens to an HTTP cookie instead of localStorage Or, keep tokens to your React app’s state
  • Tokens should be kept in backend, it would be easy to sign and verify these keys at the backend side.
  • Use long and unpredictable secrets like password files when creating an account asking for strong and long password.
  • Always ensure that you use HTTPS in place of HTTP. This will give assurance for your web-based application to provide a valid certificate that can be sent over a secure SSL network.

4.2. Broken access control-

In appropriate management of restrictions and limitations on authenticated users can use misuse of unauthorized data and functionality of React native app. In some cases unauthorized users can also change the primary key of data and control the functionality of the application. To ensure security from unauthorized access, follow these practices:

  • Deny functionality access to secure app
  • Add role-based authentication mechanism to react code

4.3 Secure Against DDoS Attacks-

Security issues that occur when the app has loopholes and it masks the IPs. This will confine the communication caused because of the termination of services. Here are some methods to stop this:

  • Add app-level restrictions to API
  • Limitation of rate on APIs- It adds limitations to the various requests for given IP from a particular source with a set of libraries using Axios-rate limit.

4.4 SQL Injection-

It is related to data manipulation. Because of this, attackers can modify data with or without user’s permission or can get any confidential information by executing arbitrary SQL code.

Solution to this is-

To avoid the SQL injection attacks, first validate API call functions against respective API schemas. So as to handle the issue of time-based SQL injection attacks, you can use timely validation of schema to avoid any suspicious code injections. Other effective way to secure against SQL vulnerability is using SSL Certificate.

4.5 Cross-Site Scripting (XSS)-

  • Discard malicious and invalid user input from being added into browser
  • Create automated overseeing features that can sanitize user input

Wrap Up-

Here you came to know, how to add security to react software. The React best practices will offer you some typing options and more explicit codes. The above react best practices will help you to eliminate any future development complication and also keep you project on the right track. We at solace infotech follows react best practices and develop secured react software. If you are thinking to develop a software with React, consult with Solace experts. We are here to help you through consultation and development. You can hire react developers of Solace team for an effective and secured react development. We will be happy to help you.  


 Article keywords:
react, react development, reactjs, software

 


 Share this article: 
Print Digg StumbleUpon del.icio.us Facebook Yahoo! Buzz Twitter Google Bookmarks LinkedIn MySpace Orkut PDF Scoopeo Viadeo Add to favorites
      

© Copyright - Articles XP