21 Best Practices for a Clean React Project
Tags: react, javascript, programming, aws
Published: 2023-08-03 08:47:26

**_To read more articles like this, [visit my blog](https://www.mdfaisal.com/blog)_**



React is very unopinionated about how things should be structured. This is exactly why it’s our responsibility to keep our projects clean and maintainable.

Today, we will discuss some best practices to improve your React application’s health. These rules are widely accepted. As such, having this knowledge is imperative.

Everything will be shown with code, so buckle up!

## 1. Use JSX ShortHand

Try to use JSX shorthand for passing boolean variables. Let’s say you want to control the title visibility of a Navbar component.

### Bad

```js
return (
  <Navbar showTitle={true} />
);
```

### Good

```js
return(
  <Navbar showTitle />  
)
```

## 2. Use Ternary Operators

Let’s say you want to show a user’s details based on role.

### Bad

```js
const { role } = user;

if(role === ADMIN) {
  return <AdminUser />
}else{
  return <NormalUser />
} 
```

### Good

```js
const { role } = user;

return role === ADMIN ? <AdminUser /> : <NormalUser />
```

## 3. Take Advantage of Object Literals

Object literals can help make our code more readable. Let’s say you want to show three types of users based on their roles. You can’t use ternary because the number of options exceeds two.

### Bad

```js
const {role} = user

switch(role){
  case ADMIN:
    return <AdminUser />
  case EMPLOYEE:
    return <EmployeeUser />
  case USER:
    return <NormalUser />
}
```

### Good

```js
const {role} = user

const components = {
  ADMIN: AdminUser,
  EMPLOYEE: EmployeeUser,
  USER: NormalUser
};

const Component = components[role];

return <Componenent />;
```

It looks much better now.

## 4. Use Fragments

Always use `Fragment` over `Div`. It keeps the code clean and is also beneficial for performance because one less node is created in the virtual DOM.

### Bad

```js
return (
  <div>
     <Component1 />
     <Component2 />
     <Component3 />
  </div>  
)
```

### Good

```js
return (
  <>
     <Component1 />
     <Component2 />
     <Component3 />
  </>  
)
```

## 5. Don't Define a Function Inside Render

Don’t define a function inside render. Try to keep the logic inside render to an absolute minimum.

### Bad

```js
return (
    <button onClick={() => dispatch(ACTION_TO_SEND_DATA)}>    // NOTICE HERE
      This is a bad example 
    </button>  
)
```

### Good

```js
const submitData = () => dispatch(ACTION_TO_SEND_DATA)

return (
  <button onClick={submitData}>  
    This is a good example 
  </button>  
)
```

## 6. Use Memo

`React.PureComponent` and `Memo` can significantly improve the performance of your application. They help us to avoid unnecessary rendering.

### Bad

```js
import React, { useState } from "react";

export const TestMemo = () => {
  const [userName, setUserName] = useState("faisal");
  const [count, setCount] = useState(0);
  
  const increment = () => setCount((count) => count + 1);
  
  return (
    <>
      <ChildrenComponent userName={userName} />
      <button onClick={increment}> Increment </button>
    </>
  );
};

const ChildrenComponent =({ userName }) => {
  console.log("rendered", userName);
  return <div> {userName} </div>;
};
```

Although the child component should render only once because the value of count has nothing to do with the `ChildComponent` . But, it renders each time you click on the button.

![](https://cdn-images-1.medium.com/max/3838/1*UC19Qvfj06VAy63lR8mOFg.png)

### Good

Let’s edit the `ChildrenComponent` to this:

```js
import React ,{useState} from "react";

const ChildrenComponent = React.memo(({userName}) => {
    console.log('rendered')
    return <div> {userName}</div>
})
```

Now, no matter how many times you click on the button, it will render only when necessary.

## 7. Put CSS in JavaScript

Avoid raw JavaScript when writing React applications because organizing CSS is far harder than organizing JS.

### Bad

```js
// CSS FILE

.body {
  height: 10px;
}

//JSX

return <div className='body'>
   
</div>
```

### Good

```js
const bodyStyle = {
  height: "10px"
}

return <div style={bodyStyle}>

</div>
```

## 8. Use Object Destructuring

Use object destructuring to your advantage. Let’s say you need to show a user’s details.

### Bad

```js
return (
  <>
    <div> {user.name} </div>
    <div> {user.age} </div>
    <div> {user.profession} </div>
  </>  
)
```

### Good

```js
const { name, age, profession } = user;

return (
  <>
    <div> {name} </div>
    <div> {age} </div>
    <div> {profession} </div>
  </>  
)
```

## 9. String Props Don’t Need Curly Braces

When passing string props to a children component.

### Bad

```js
return(
  <Navbar title={"My Special App"} />
)
```

### Good

```js
return(
  <Navbar title="My Special App" />  
)
```

## 10. Remove JS Code From JSX

Move any JS code out of JSX if that doesn’t serve any purpose of rendering or UI functionality.

### Bad

```js
return (
  <ul>
    {posts.map((post) => (
      <li onClick={event => {
        console.log(event.target, 'clicked!'); // <- THIS IS BAD
        }} key={post.id}>{post.title}
      </li>
    ))}
  </ul>
);
```

### Good

```js
const onClickHandler = (event) => {
   console.log(event.target, 'clicked!'); 
}

return (
  <ul>
    {posts.map((post) => (
      <li onClick={onClickHandler} key={post.id}> {post.title} </li>
    ))}
  </ul>
);
```

## 11. Use Template Literals

Use template literals to build large strings. Avoid using string concatenation. It’s nice and clean.

### Bad

```js
const userDetails = user.name + "'s profession is" + user.proffession

return (
  <div> {userDetails} </div>  
)
```

### **Good**

```js
const userDetails = `${user.name}'s profession is ${user.proffession}`

return (
  <div> {userDetails} </div>  
)
```

## 12. Import in Order

Always try to import things in a certain order. It improves code readability.

### Bad

```js
import React from 'react';
import ErrorImg from '../../assets/images/error.png';
import styled from 'styled-components/native';
import colors from '../../styles/colors';
import { PropTypes } from 'prop-types';
```

### Good

The rule of thumb is to keep the import order like this:

* Built-in

* External

* Internal

So the example above becomes:

```js
import React from 'react';

import { PropTypes } from 'prop-types';
import styled from 'styled-components/native';

import ErrorImg from '../../assets/images/error.png';
import colors from '../../styles/colors';
```

## 13. Use Implicit return

Use the JavaScript feature implicit `return` in writing beautiful code. Let’s say your function does a simple calculation and returns the result.

### Bad

```js
const add = (a, b) => {
  return a + b;
}
```

### Good

```js
const add = (a, b) => a + b;
```

## 14. Component Naming

Always use PascalCase for components and camelCase for instances.

### Bad

```js
import reservationCard from './ReservationCard';

const ReservationItem = <ReservationCard />;
```

### Good

```js
import ReservationCard from './ReservationCard';

const reservationItem = <ReservationCard />;
```

## 15. Reserved Prop Naming

Don’t use DOM component prop names for passing props between components because others might not expect these names.

### Bad

```js
<MyComponent style="dark" />

<MyComponent className="dark" />
```

### Good

```js
<MyComponent variant="fancy" />
```

## 16. Quotes

Use double quotes for JSX attributes and single quotes for all other JS.

### Bad

```js

<Foo bar='bar' />

<Foo style={{ left: "20px" }} />
```

### Good

```js
<Foo bar="bar" />

<Foo style={{ left: '20px' }} />
```

## 17. Prop Naming

Always use camelCase for prop names or PascalCase if the prop value is a React component.

### Bad

```js
<Component
  UserName="hello"
  phone_number={12345678}
/>
```

### Good

```js
<MyComponent
  userName="hello"
  phoneNumber={12345678}
  Component={SomeComponent}
/>
```

## 18. JSX in Parentheses

If your component spans more than one line, always wrap it in parentheses.

### Bad

```js
return <MyComponent variant="long">
           <MyChild />
         </MyComponent>;
```

### Good

```js

return (
    <MyComponent variant="long">
      <MyChild />
    </MyComponent>
);
```

## 19. Self-Closing Tags

If your component doesn’t have any children, then use self-closing tags. It improves readability.

### Bad

```js
<SomeComponent variant="stuff"></SomeComponent>
```

### Good

```js
<SomeComponent variant="stuff" />
```

## 20. Underscore in Method Name

Do not use underscores in any internal React method.

### Bad

```js
const _onClickHandler = () => {
  // do stuff
}
```

### Good

```js

const onClickHandler = () => {
  // do stuff
}
```

## 21. Alt Prop

Always include an alt prop in your `<img >` tags. And don’t use `picture` or `image` in your alt `property` because the screenreaders already announce `img` elements as images. No need to include that.

### Bad

```js
<img src="hello.jpg" />

<img src="hello.jpg" alt="Picture of me rowing a boat" />
```

### Good

```js
<img src="hello.jpg" alt="Me waving hello" />
```

## Conclusion

There you go. Congratulations if you’ve made it this far! I hope you learned a thing or two from this article.

I hope you have a wonderful day! :D

**Have something to say?**

## Resources

* Airbnb Guideline: [https://github.com/airbnb/javascript/tree/master/react](https://github.com/airbnb/javascript/tree/master/react)

**Get in touch with me via [LinkedIn](https://www.linkedin.com/in/56faisal/) or my [Personal Website](https://www.mdfaisal.com/).**