React is one of the most popular front-end frameworks for JavaScript. Unlike other frameworks like Angular, it is very unopinionated. Therefore, it is up to you to decide how you want to write or structure your React code.

Some of React's best practices you should follow to improve the performance of your application are listed below.

1. Using Functional Components and Hooks Instead of Classes

In React, you can use class or functional components with hooks. You should, however, use functional components and hooks more often as they result in more concise and readable code compared to classes.

Consider the following class component that displays data from the NASA API.

        class NasaData extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      data: [],
    };
  }

  componentDidMount() {
    fetch("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY")
      .then((res) => res.json())
      .then((json) => {
        this.setState({
          data: json,
        });
      });
  }

  render() {
    const { data } = this.state;

    if (!data.length)
      return (
        <div>
          <h1> Fetching data.... </h1>{" "}
        </div>
      );

    return (
      <>
        <h1> Fetch data using Class component </h1>{" "}
        {data.map((item) => (
          <div key={item.id}>{item.title}</div>
        ))}
      </>
    );
  }
}

You can write the same component using hooks:

        const NasaData = () => {
  const [data, setdata] = useState(null);

  useEffect(() => {
    fetch("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY")
      .then((res) => res.json())
      .then((json) => {
        setdata(json);
      });
  }, [data]);

  return (
    <>
      <h1> Fetch data using Class component </h1>{" "}
      {data.map((item) => (
        <div key={item.id}>{item.title}</div>
      ))}
    </>
  );
};

Even though the above block of code does the same thing as the class component, it is less complex, minimal, and easy to understand.

2. Avoid Using State (if Possible)

React state keeps track of the data which when changed triggers the React component to re-render. When building React applications, avoid using state as much as possible since the more state you use, the more data you have to keep track of across your app.

One way of minimizing the use of state is by declaring it only when necessary. For instance, if you are fetching user data from an API, store the whole user object in the state instead of storing the individual properties.

Instead of doing this:

        const [username, setusername] = useState('')
const [password, setpassword] = useState('')

Do this:

        const [user, setuser] = useState({})
    

When deciding on a folder structure for your React app, go for a component-centric one. This means storing all the files concerning one component in one folder.

If you were creating a Navbar component, for example, create a folder named Navbar containing the component file, the style sheet, and other JavaSript and asset files used in the component.

A single folder containing all of a component’s files makes it easy to reuse, share, and debug. If you need to see how a component works you only need to open a single folder.

Other React folder best practices are:

  1. Use index files to abstract the implementation details of your component file. Considering the Navbar example, create a Navbar folder and in this folder add a component file named index.js (or .ts) file.
  2. Keep reusable components in a separate folder. If you have components that more than one part of your application use, consider keeping them in a folder named components. This will help you locate them easily.
  3. Keep utility functions in a separate folder such as a lib or helpers folder. This will make it easier to manage and reuse these functions later on.

4. Avoid Using Indexes as Key Props

React uses keys to uniquely identify items in an array. With keys, React can pinpoint which item has been changed, added, or removed from the array.

When rendering arrays, you might use the index as the key.

        const Items = () => {
  const arr = ["item1", "item2", "item3", "item4", "item5"];

  return (
    <>
      {arr.map((elem, index) => {
        <li key={index}>{elem}</li>;
      })}
    </>
  );
};

While this sometimes works, using the index as a key can introduce issues especially if the list is expected to change. Consider this list.

        const arr = ["item1", "item2", "item3", "item4", "item5"];
    

Currently, the first list item, “Item1” is at index zero, but if you added another item at the beginning of the list, the “Item1” index would change to 1 which changes the behavior of your array.

The solution is to use a unique value as the index to ensure that the identity of the list item is maintained.

5. Opt for Fragments Instead of Divs Where Possible

React components need to return code wrapped in a single tag usually a <div> or a React fragment. You should opt for fragments where possible.

Using <div> increases the DOM size, especially in huge projects since the more tags or DOM nodes you have, the more memory your website needs and the more power a browser uses to load your website. This leads to lower page speed and potentially poor user experience.

One example of eliminating unnecessary <div> tags is not using them when returning a single element.

        const Button = () => {
  return <button>Display</button>;
};

6. Follow Naming Conventions

You should always use PascalCase when naming components to differentiate them from other non-component JSX files. For example: TextField, NavMenu, and SuccessButton.

Use camelCase for functions declared inside React components like handleInput() or showElement().

7. Avoid Repetitive Code

If you notice you are writing duplicated code, convert it into components that can be reused.

For example, it makes more sense to create a component for your navigation menu instead of repeatedly writing the code in every component that requires a menu.

That’s the advantage of a component-based architecture. You can break down your project into small components you can reuse across your application.

8. Use Object Destructuring For Props

Instead of passing the props object, use object destructuring to pass the prop name. This discards the need to refer to the props object each time you need to use it.

For example, the following is a component that uses props as is.

        const Button = (props) => {
  return <button>{props.text}</button>;
};

With object destructuring, you refer to the text directly.

        const Button = ({text}) => {
  return <button>{text}</button>;
};

9. Dynamically Render Arrays Using Map

Use map() to dynamically render repeated HTML blocks. For example, you can use map() to render a list of items in <li> tags.

        const Items = () => {
  const arr = ["item1", "item2", "item3", "item4", "item5"];

  return (
    <>
      {arr.map((elem, index) => {
        <li key={elem+index}>{elem}</li>;
      })}
    </>
  );
};

For comparison purposes, here is how you can render the list without map(). This approach is very repetitive.

        const List = () => {
  return (
    <ul>
      <li>Item1</li>
      <li>Item2</li>
      <li>Item3</li>
      <li>Item4</li>
      <li>Item5</li>
    </ul>
  );
};

10. Write Tests for Each React Component

Write tests for the components you create as it reduces the possibility of errors. Testing ensures that the components are behaving as you would expect. One of the most common testing frameworks for React is Jest, and it provides an environment where you can execute your tests.

React Is a Powerful Tool, but You Must Follow Certain Practices

Although React is very flexible in how you can use it, following specific practices will help you get the most out of your experience.

When following these tips, keep your particular project and goals in mind as different React best practices may be more relevant in different contexts. For instance, a project with a small team and a limited scope may not require the same level of folder organization as a large project with multiple teams working together.