React best practices and patterns to reduce code - Part 2
Tags: react, reactnative, redux, javascript
Published: 2022-03-18 18:31:24

I've another article about React best practices and patterns to reduce code. It's a good article to read before you start to write your own React code. 
###### [React best practices and patterns to reduce code - Part 1](https://dev.to/devsmitra/react-best-practices-and-patterns-to-reduce-code-2bff)

[![React best practices and patterns to reduce code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9qfo68lckofw16nfgp16.png)](https://www.youtube.com/watch?v=Y85X4PiuuTM)

Without wasting time, let's look at some more best practices and patterns to reduce code. We'll start with the most common ones.

#### If the component doesn't have children's props, use the self-closing tag.

###### Bad code:

```javascript
return <Component></Component>;
```

###### Good code:

```javascript
return <Component />;
```

---

#### Don't write functions inside jsx elements.

###### Bad code:

```javascript
return (
  <div>
    <button
      onClick={() => {
        setCount(1);
        // ...
      }}
    >
      Click
    </button>
  </div>
);
```

###### Good code:

```javascript
const onClick = useCallback(() => {
  setCount(1);
  // ...
}, [deps]);

return (
  <div>
    <button onClick={onClick}>Click</button>
  </div>
);
```

---

#### Use object state if you have to update multiple states together.

Avoid using multiple setState calls in a row. This is a common mistake that can lead to a lot of unnecessary re-renders. It's better to use a single setState call.

###### Bad code:

```javascript
const [count, setCount] = useState(0);
const [name, setName] = useState("");

const onClick = () => {
  setTimeout(() => {
    setName("John");
    setCount(count + 1);
  }, 1000);
};
```

###### Good code:

```javascript
const [state, setState] = useState({
  count: 0,
  name: "",
});

const onClick = () => {
  setTimeout(() => {
    setState((prevState) => ({
      ...prevState,
      name: "John",
      count: prevState.count + 1,
    }));
  }, 1000);
};
```

**_Note:_** React 18 adds automatic batching, so multiple updates will be taken care by react itself.


---

#### Use styled-components to style your components. This is a good way to avoid writing CSS in JSX and also helps to avoid CSS setup for the application.

> It's completely opinion based.

###### Bad code:

```javascript
return <div style={{ backgroundColor: "red" }}></div>;
```

###### Good code:

```javascript
const Container = styled.div`
  background-color: ${({ theme }) => theme.colors.background};
  padding: 1rem;
`;
```

###### Better code:

```javascript
const getPrimaryColor = ({ theme }) => theme.colors.primary;
const getDefaultColor = ({ theme }) => theme.colors.secondary;

const Button = styled.button`
  background-color: ${getPrimaryColor};
  color: ${getDefaultColor};
`;
```

**_Note:_** Create functions to get color and other styles from the theme and pass them to styled components. This will also help to reduce code.

---

#### Try to avoid class-based components and use functional components instead.

###### Bad code:

```javascript
class Counter extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
    this.onClick = this.onClick.bind(this);
  }

  onClick = () => {
    this.setState({
      count: this.state.count + 1,
    });
  };

  render() {
    return <button onClick>Click me</button>;
  }
}
```

###### Good code:

```javascript
const Counter = () => {
  const [count, setCount] = useState(0);
  const onClick = () => setCount(count + 1);
  return <button>Click me</button>;
};
```

**_NOTE:_** Functional components not only reduces development time and code but also decrease production bundle size. It reduces the bundle size by almost ~60%.

---

#### React.memo to avoid unnecessary re-renders.

###### Bad code:

```javascript
return (
  <ui>
    {items.map((item) => (
      <Component>{item}</Component>
    ))}
  </ui>
);
```

###### Good code:

```javascript
const MemoComponent = React.memo(Component);
return (
  <ui>
    {items.map((item) => (
      <MemoComponent>{item}</MemoComponent>
    ))}
  </ui>
);
```

**_NOTE_**: Use `React.memo()` wisely, don't use memo where component often re-renders with props.

---

#### Use JSX ShortHand, Try to use JSX shorthand for passing boolean variables.

###### Bad code:

```javascript
return <button disabled={true}>Submit</button>;
```

###### Good code:

```javascript
return <button disabled>Submit</button>;
```

---

#### Use ternary operator instead of if-else statement.

###### Bad code:

```javascript
if (isLoading) {
  return <div>Loading...</div>;
} else {
  return <div>Data</div>;
}
```

###### Good code:

```javascript
return isLoading ? <div>Loading...</div> : <div>Data</div>;
```

---

#### Use object(Map) instead of switch statement. I've already mentioned the same in my previous article for reducers.

###### Bad code:

```javascript
switch (props.type) {
  case "ADMIN":
    return <Admin />;
  case "USER":
    return <User />;
  default:
    return <NotFound />;
}
```

###### Good code:

```javascript
const componentMap = {
  ADMIN: Admin,
  USER: User
};

const Component = componentMap[props.type] ?? NotFound;
return <Component />;
```

###### Better code:

```javascript
const NotFound = React.lazy(() => import("../components/NotFound"));
const componentMap = {
  ADMIN: React.lazy(() => import("../components/Admin")),
  USER: React.lazy(() => import("../components/User")),
};

const Component = componentMap[props.type] ?? NotFound;
return <Component />;
```

---

#### Use object destructuring instead of passing multiple props by name to a component.

###### Bad code:

```javascript
const { name, age, role } = props;
return (
  <>
    <Component name={name} age={age} role={role} />
  </>
);
```

###### Good code:

```javascript
return (
  <>
    <Component {...props} />
  </>
);
```

---

#### Don't need curly braces when you won't pass the string to a component.

###### Bad code:

```javascript
return <Component name={"John"} />;
```

###### Good code:

```javascript
return <Component name="John" />;
```

---

#### Don't use react element props like `className`, `style` etc for component custom props.

###### Bad code:

```javascript
return (
  <Component style="bordered">
);
```

###### Good code:

```javascript
return (
  <Component variant="bordered">
);
```

---

#### Use fragment instead of html element like div, span, etc.

###### Bad code:

```javascript
return (
  <div>
    <span>{props.name}</span>
    <span>{props.age}</span>
  </div>
);
```

###### Good code:

```javascript
return (
  <>
    <span>{props.name}</span>
    <span>{props.age}</span>
  </>
);
```

---

#### Don't use else block if `if` block returns something.

###### Bad code:

```javascript
if (props.name) {
  return <div>{props.name}</div>;
} else {
  return <div>No name</div>;
}
```

###### Good code:

```javascript
if (props.name) {
  return <div>{props.name}</div>;
}
return <div>No name</div>;
```

---

#### Use React.fragment instead of Html element like div, span, etc when you won't use the `key` property.

###### Bad code:

```javascript
return (
  <container>
    {list.map((item) => (
      <div key={item.id}>
        <SomeComponent />
        <SomeAnotherComponent />
      </div>
    ))}
  </container>
);
```

###### Good code:

```javascript
return (
  <>
    {list.map((item) => (
      <React.Fragment key={item.id}>
        <SomeComponent />
        <SomeAnotherComponent />
      </React.Fragment>
    ))}
  </>
);
```

Thank you for reading 😊

Got any questions or additional? please leave a comment.


---

### Must Read If you haven't

{% link https://dev.to/devsmitra/no-more-redux-action-creators-functions-30j %}
{% link https://dev.to/devsmitra/how-to-cancel-javascript-api-request-with-abortcontroller-36cm %}
{% link https://dev.to/devsmitra/13-typescript-utility-a-cheat-sheet-for-developer-ab3 %}
{% link https://dev.to/devsmitra/how-to-solve-rest-api-routing-problem-with-decorators-5b3n %}


### Catch me on
{% user devsmitra %}
<p>
{% cta https://www.youtube.com/@devsmitra?sub_confirmation=1 %} Youtube {% endcta %}
{% cta https://github.com/devsmitra %} Github {% endcta %}
{% cta https://www.linkedin.com/in/rahul-sharma-18b8b374 %} LinkedIn {% endcta %}
{% cta https://devsmitra.medium.com %} Medium {% endcta %}
{% cta https://stackblitz.com/@devsmitra %} Stackblitz {% endcta %} {% cta https://devsmitra.hashnode.dev %} Hashnode {% endcta %}
{% cta https://hackernoon.com/u/devsmitra %} HackerNoon {% endcta %}
</p>