The Talent500 Blog
React JS Best Practices to follow in 2023 1

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.

React JS Best Practices to follow in 2023 2

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:

  • Root Structure
  • src (Source Directory)
    • components
    • containers/pages
    • services/APIs
    • styles
    • assets
    • utils (utilities)
  • Configuration Files (e.g., Webpack, environment variables)
  • Tests

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:

  • Make components independent: When you are creating a component, make it as minimal as possible. It will make your development as well as the post-development process much easier. 
  • Make it reusable: As the component becomes independent, you can reuse the component in other sections of the websites and you can pass data as props and make it dynamic.
  • Extracting Logic: If you are using the same logic in multiple places, instead of repeating yourself, you can make a separate module/file which you can reuse by importing the function.
  • Use Libraries and Utilities: Leverage existing libraries and utility functions to handle common tasks instead of reinventing the wheel. For example, libraries like lodash can help with data manipulation, validation, and other common operations.

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:

  • Use Descriptive and Clear Names: Choose component names that accurately describe their purpose and functionality.
  • Capitalize Component Names: This convention helps differentiate components from regular HTML elements and allows React to distinguish between them during the compilation process.
  • Avoid Generic Names and Ambiguity: Avoid generic or ambiguous names that do not provide enough context about the component’s purpose or usage. Generic names like Wrapper, Container, or Item can quickly become confusing when working with multiple components or a large codebase.
  • Use CamelCase for Multi-Word Names: When a component name consists of multiple words, use CamelCase (also known as PascalCase) to distinguish between the words. For example, LoginForm, UserProfile, or SearchResults. 

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:

  • Type Safety and Error Detection: TypeScript helps identify common mistakes and potential bugs before runtime. It provides a safety net, allowing you to detect and fix issues early in the development process.
  • Improved Code Maintainability:  By specifying types for variables, function parameters, and return values, you make the code self-documenting.
  • Enhanced Tooling and IDE Support: TypeScript comes with a rich set of tools and IDE support. Popular editors like Visual Studio Code provide intelligent autocompletion, code navigation, and refactoring capabilities specific to TypeScript.
  • Scalability and Refactoring: TypeScript helps in refactoring efforts by providing a safety net during code modifications. Static typing allows you to make changes confidently, knowing that the compiler will highlight any breaking changes and guide you in updating the affected areas.

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:

  • In-built Routing: Next.js provides a similar routing which is like folder and file-based routing. You can create a folder, which will be the URL of the page and inside the page.jsx file, you can write the logic for that part.
  • Full-stack capabilities: Next.js provides full-stack capabilities, allowing you to build both the front-end and back-end of your application using a single framework. This eliminates the need for separate server-side frameworks and simplifies the development process.
  • Better SEO: Next.js enables search engines to crawl and index your website effectively, resulting in improved search engine rankings and better discoverability.
  • Inbuilt Image Optimization: Next.js provides built-in image components that automatically optimize images with a powerful native API. This feature is game-changing, improving the experience for both developers and users alike.

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
Adarsh M

Adarsh M

A soon-to-be engineer and software developer. Curious about advanced tools and Web technologies. Loves to be a part of fast moving technical world.

Add comment