The Talent500 Blog

React JS Best Practices to follow in 2023

We all know the popularity of React has been growing exponentially, and an increasing number of Fortune 500 companies are building their web applications on top of React. Approximately 18 million projects utilize React every week. React has maintained its dominance in the web development market for over nine years.

Undoubtedly, React is the most popular front-end library and one of the trendiest technologies to learn. According to the 2022 State of JS survey, React holds the top position in terms of usage.

In this detailed blog, we will explore some of the best practices that you should follow as a React developer. So Let’s get started.

File and folder organization 

One of the biggest challenges faced by React developers is maintaining project organization. When files and folders are mixed up, it becomes difficult for maintainers to navigate and manage the codebase effectively.

One good approach is to divide the folder structures into a more self-explanatory structure. For example:

The above structure is a very basic one; for complicated projects, you can choose a much more maintainable folder structure. If you are using frameworks like Next.js, you will already have a default structure that you need to follow.

Keep your code DRY

React came into existence for one main reason: to make web development easier. Keeping your React code “DRY” (Don’t Repeat Yourself) is a best practice that can improve code maintainability, reduce duplication, and enhance overall development efficiency. Here are some tips for keeping your React codebase DRY:

Use Hooks

React Hooks became very popular and it is now the standard way of doing things in React. Most developers don’t know most of the hooks. Two popular hooks are useState() and useEffect(). But there may be situations where you can more appropriate hooks.

When a parent component renders, all child components typically re-render, even if their props haven’t changed. However, by using use callback, you can memoize the callback function and prevent unnecessary re-renders of child components that depend on that callback.

Avoid Using Indexes as a Key Prop

When rendering lists in React, it’s essential to assign unique keys to each item. Keys allow React to identify items within an array accurately, making it easier to determine which items have been inserted, modified, or removed. While it may be tempting to use the index of the array as the key, it can lead to problems when the list of items changes.

const Items = () => {

  const arr = [“apple”, “banana”, “cat”, “dog”, “egg”];

return (

    <>

      {arr.map((elem, index) => (

        <li key={elem}>{elem}</li>

      ))}

    </>

  );

};

While using the index as the key occasionally works, it can cause issues when the list undergoes expected changes. One way to solve this is using the item value itself as the key, we ensure that each item is uniquely identified within the array. This approach allows React to accurately track changes in the list, even if the order or position of items changes dynamically.

You can also use UUID, which gives you a unique value. But if you are just rendering less than 50 (not a specific number) list, you are totally fine using the key as the actual value in the array.

Component Naming

Properly naming your components is a crucial aspect of writing clean and maintainable React code. Better component names enhance code readability and understanding, making it easier for you and other developers to navigate and work with your codebase.

When naming your components, consider the following best practices:

Opt for React Fragments Over divs

When returning code from a React component, it’s common to wrap it in a single tag. The traditional approach has been to use <div> as the wrapping element. However, it’s considered a best practice to utilize React fragments instead.

Every HTML tag or <div> you use in your code comes with an associated memory cost. As the number of <div> tags increases, so does the memory required by your website. This additional memory usage leads to higher power consumption and increased loading times, ultimately resulting in a slower website speed and a subpar user experience.

React fragments provide a solution to this problem. Fragments allow you to group elements without introducing any extra nodes in the DOM. Unlike <div>, fragments don’t create additional elements, reducing the memory footprint and improving overall performance.

const MyComponent = () => {

  return (

    <>

      <h1>Heading</h1>

      <p>Paragraph 1</p>

      <p>Paragraph 2</p>

    </>

  );

};

export default MyComponent;

Prefer Passing Objects

When passing data to components in React, it’s common to pass sets of primitive values as separate props. However, to streamline and organize the data being passed, it is recommended to prefer passing an object instead. By encapsulating related properties within an object, you can reduce the number of props being passed and improve code maintainability.

For example, this is an anti-pattern

const EmployeeAccount = ({ name, age, department,position}) => {

  return (

    <div>

      <h2>{name}</h2>

      <p> {age}</p>

      <p>Dept: {department}</p>

      {/* Additional employee details can be accessed from the ‘user’ object */}

    </div>

  );

};

const MyComponent = () => {

return(

      <EmployeeAccount name={“your name”} age={7} position={“engineer”} department=”testing” />

)

}

You can do this in a much simpler and better way, like this:

const EmployeeAccount = ({ user }) => {

  return (

    <div>

      <h2>{user.name}</h2>

      <p>Email: {user.email}</p>

      <p>ID: {user.id}</p>

      {/* Additional employee details can be accessed from the ‘user’ object */}

    </div>

  );

};

const MyComponent = () => {

  const user = {

    name: ‘John Doe’,

    email: ‘johndoe@example.com’,

    id: 12345,

    // Additional employee details

    position: ‘Software Engineer’,

    Department: ‘Engineering’,

  };

  return (

    <div>

      <EmployeeAccount user={user} />

    </div>

  );

};

Avoid Mixing Data and Logic in Components

In React, it is considered a good practice to separate the presentation and business logic within your components. However, there might be instances where the temptation arises to mix data and logic within a component. This often stems from the desire to ensure data availability for other parts of the application.

To address this, creating a new component specifically responsible for managing the data and displaying it on the page is recommended. This approach is commonly referred to as a smart component. By separating the business logic and data presentation into distinct components, you can encapsulate the logic and data to display it on the page.

Embrace the Power of TypeScript in React Development

Although React offers flexibility and efficiency, the use of plain JavaScript leaves room for potential errors and difficulties in maintaining larger codebases. This is where TypeScript comes into play.

TypeScript is a statically-typed superset of JavaScript that brings additional benefits to React development. By adding static typing and other language features, TypeScript provides several advantages for building robust and scalable React applications.

Some of the benefits of using TypeScript are:

Start using Next.js

React has made it easy for front-end developers to create applications using component-based architecture and a declarative approach. However, when it comes to building complex applications with server-side rendering (SSR), routing, and optimized performance, Next.js emerges as a valuable tool in the React ecosystem.

Some of the advantages of using Next.js are:

There are many such industry practices that you can follow so that your code can be much more readable and maintainable. 

Wrapping it Up!

Congratulations on making it to the end of this blog!

In this detailed blog, we have looked at various best practices to follow. We have also looked into the advantages of using TypeScript and Next js. Following these industry practices, developers can benefit from enhanced efficiency, improved code quality, etc. 

Happy Learning!  

 

 

0