Introduction
React is a library that is highly popular because of its features and functionalities provided for developing web and mobile apps. Its simplicity and flexibility allow developers to build applications quickly and it is estimated that more than 1300 developers and 90,000+ sites utilize ReactJS. You can create large web apps that can change data without reloading the page repetitively. It is used for handling the view layer and creating reusable UI components.
React has evolved quite a lot in recent years, and has several modern and new features introduced. If you’re planning to build a ReactJS application, then you’re reading the perfect blog where we’re going to discuss the top React practices to adapt in 2021. So, let’s get started!
React JS Best Practices to Learn and Adapt in 2021
- Use Higher Order Functions
In React, one of the best ways to achieve the DRY principle that is Don’t Repeat Yourself across components is to make use of the Higher-Order Component concept. You can use the same functionality without writing code using HOCs. The higher-order component is important for each function that takes in a component as an argument and then it returns a new component. It also renders the original component that was passed to it as an argument.
function myHOC (myOtherComponent) {
return class extends React.Component { render() { return <myOtherComponent {…this.props}/> } } } |
HOC allows you to abstract your code and get a hang of it using this pattern too often. You can always follow DRY principles even without implementing HOCs.
- Use Ternary Operator
Let’s say you want to show a particular user’s details based on their role.
Bad:
const { role } = user;
if(role === ADMIN) { return <AdminUser /> }else{ return <NormalUser /> } |
Good:
const { role } = user;
return role === ADMIN ? <AdminUser /> : <NormalUser /> |
- Custom Hooks
You must make sure a React component is only displayed when a user is logged in to your application. You will do sanity checks while rendering until you introduce that you are actually repeating yourself a lot. Have a look at the following example given below:
import { useEffect } from ‘react’;
import { useAuth } from ‘./use-auth-from-context-or-state-management.js’; import { useHistory } from ‘react-router-dom’; function useRequireAuth(redirectUrl = “/signup”) { const auth = useAuth(); const history = useHistory(); // If auth.user is false that means we’re not // logged in and should redirect. useEffect(() => { if (auth.user === false) { history.push(redirectUrl); } }, [auth, history]); return auth; } |
As you can see in the above-mentioned example, the useRequireAuth hook will check if a user is logged in to the application, or else it will be redirected to a different page.
- Render Props
The word Render Prop was introduced by Michael Jackson, who suggested that the HOC pattern could be replaced 100% of the time with a regular component with a “render prop”. As we all know that all React components are functions that are passed as props.
Here is the code to generalize how to obtain data from an API and fetch logic into a useFecth hook further from the UI.
import { useEffect, useState } from “react”;
export default function Fetch({ render, url }) { const [state, setState] = useState({ data: {}, isLoading: false }); useEffect(() => { setState({ data: {}, isLoading: true }); const _fetch = async () => { const res = await fetch(url); const json = await res.json(); setState({ data: json, isLoading: false, }); } _fetch(); }, https%3A%2F%2f Editor.sitepoint.com); return render(state); } |
Here is a property called Render, which is a function called during the rendering process and gets the complete state with its parameter.
<Fetch
url=”https://api.github.com/users/imgly/repos” render={({ data, isLoading }) => ( <div> <h2>img.ly repos</h2> {isLoading && <h2>Loading…</h2>} <ul> {data.length > 0 && data.map(repo => ( <li key={repo.id}> {repo.full_name} </li> ))} </ul> </div> )} /> |
Here you can see that is loading parameters and data are eliminated from the state object and used to drive the response of the JSX. However, it is a very powerful mechanism to obtain common UI behavior.
- Test your code
Lastly, test your code! Once you follow all the best React JS practices, make sure to test your code and make it easy to test. There are various types of testing that you can implement with your React app and we recommend using all of them.
End to end testing
End-to-end testing is basically testing the application as a whole. It imitates how a user will click through the app and test it in a web browser. One of the most simple and easy ways to use a framework for end-to-end testing JavaScript is Cypress.
Unit testing
For unit testing, Jest is the best and popular platform that developers use. Other frameworks like Mocha that you can use for Unit testing which is the basic form of testing and allows you to test the smallest units in your code.
Component Testing
As we all know that everything in React is a component and follows the component-based approach. These React components are reusable units that can be tested efficiently.
Wrapping Up
We hope you find the article helpful and sheds some light on ReactJS best practices that are very popular in 2021 and beyond. React has been used widely and it is also evolving by the day.
Readers, if you’re still reading this article, then congratulations you’ve made it this far! So, before you take initiative to develop your project using React, make sure to go through the best ReactJS practices and make your development process simple and flexible.