3 Best Practices for Working With React Components
Tags: react, components, programming
Published: 2018-09-06 19:34:39

---
title: 3 Best Practices for Working With React Components
published: true
description: 
tags: react, react.js, components, programming
cover_image: https://thepracticaldev.s3.amazonaws.com/i/80z6z5u3qwh60yci7cmp.png
canonical_url: https://blog.liveedu.tv/3-best-practices-for-working-with-react-components
---

(This article was originally published on our blog [here](https://blog.liveedu.tv/3-best-practices-for-working-with-react-components/) ). 

[React.js](https://reactjs.org/) (also referred to as ReactJS or React) is a popular JavaScript library for creating wonderful user interfaces. 
  

One of the notable features of React is that it relies on a component-focused approach for building interactive UIs.   
  

Maxim-Filimonov, who has more than ten years of experience in the software development industry and presently teaches people his skills, says that “adhering to the React API best practices when creating components will assist you to write high-quality and clean React code.”
  

[Click here](https://www.liveedu.tv/maxim-filimonov/2b1rr-how-to-build-cross-platform-mobile-app-in-react-native/gYoKx-intro-video1/) to watch and learn from one of his projects on How to Build Cross-platform Mobile App in React Native. 

Here are three React tips and best practices you need to take your development skills a notch higher.

  
## 1. Avoid creating new components unnecessarily

  
Here is an example of a React component:

```javascript
export default class Liveedu extends PureComponent {
  static propTypes = {
    userIsLearning: PropTypes.bool,
    user: PropTypes.shape({
      _id: PropTypes.string,
    }).isNeeded,
  }

  static defaultProps = {
    userIsLearning: false,
  }

  render() {
    const { userIsLearning, user } = this.props;
    if (!userIsLearning) return <Learning />;
    return (
      <div>
        <div className="two-col">
          <section>
            <LearnOnline userId={user.id} />
            <Watching projects userId={user._id} />
          </section>
          <aside>
            <UserDetails user={user} />
            <WatchProjects user={user} />
          </aside>
        </div>
        <div className="one-col">
          {isInfo('student', user={user._id} &&
            <LearnersInfo userId={user._id} />
          }
        </div>
      </div>
    )
  }
}
```


As you can see from the above code, we have a single component called _Liveedu_. We’ve included other components like _LearnOnline_ and _WatchProjects_ inside this huge component.

  
Since we are taking all the data from the same location (_user_), we could have just declared the components separately. However, to achieve conciseness, we opted to include the smaller components inside one component.

  
Whereas there are no black and white rules concerning how to create a new component for your React code, the following guidelines are worthwhile:
  

- If you are going to reuse your code, consider creating new components for each functionality. 
- If you want each component to represent a specific functionality, then making new components can be a good idea. 
- If your code is becoming unwieldy and cluttered, improve readability by creating new components. 
  

## 2. Know when to use Component, Stateless Functional Component, and PureComponent

Another best practice when creating React code is to know when to use the various types of components.

 
Here is a code sample that shows how to create a Stateless Functional Component:

```javascript
const Liveedu = () => (
  <WatchProjects>
    <H1>Programming Projects</H1>
    <div className="learn_online">
      <Link className="liveedu_project_image" to="/">
        <img alt="experts building projects" src="liveedu.jpg">
      </Link>
      <div className="Project Learning Platform">
        <h2 className="create">Programming Projects</h2>
        <li>JavaScript</li>
        <li>PHP</li>
        <li>Angular</li>
      </div>
    </div>
  </WatchProjects>
);
```


This type of component will assist you to write clean and uncluttered React code. 

You can use them to make components that are not relying on any type of _refs_, _state_, or other _lifecycle methods_. 

Therefore, you’ll not be concerned about state manipulation or lifecycle methods, which will not force you to install libraries for performing tests.

Just like the name suggests, this component is without any state; it’s just a function. Therefore, it assists you to define a component just like a constant function that returns the required data.

In other words, it is a function that is used to return JSX. 

 
In the above first code sample, you might have realized that we declared _Liveedu_ as _PureComponent_ instead of using the traditional _Component_.
  

_PureComponent_ is often used to prevent React from re-rendering unnecessarily. Whenever a component receives a new prop, it will automatically be re-rendered. 

This will take place even when a component has received a new prop without any changes.

For example, if a prop is referencing a string or Boolean value, and changes take place, a _PureComponent_ can detect that. 

On the other hand, whenever a property inside an object experiences any changes, a _PureComponent_ cannot initiate React re-rendering.

Therefore, you can use _PureComponent_ in place of _Component_ to ensure re-rendering takes place only when necessary.

  

## 3. Use spread attributes sparingly

  
The _…_ (three dots) spread operator is useful for achieving brevity in your React code. 
  

Here is a code sample that selects specific props that a component consumes and uses the spread operator to pass the entire props object

```javascript
const Liveedu = props => {
  const { kind, ...other } = props;
  const className = kind === "primary" ? "PrimaryButton" : "SecondaryButton";
  return <button className={className} {...other} />;
};

const App = () => {
  return (
    <div>
      <Button kind="primary" onClick={() => console.log("clicked to start learning")}>
        Watch Experts Create Practical Projects
      </Button>
    </div>
  );
};
```


In the above code, the _kind_ prop is consumed without any issues. Furthermore, it is not passed to the _&lt;button&gt;_ element in the Document Object Model (DOM).

Also, the other props are passed using the _…other_ object, which adds some flexibility to this component. In fact, it passes an _onClick_ and _children_ props, as shown on the code.

Whereas using spread attributes in your components can be beneficial, it increases the chances of passing needless props to components that do not care about their existence.

Furthermore, this syntax can make you pass unwarranted HTML attributes to the DOM. 

Therefore, using them sparingly is better.

## Wrapping up

React components are the cornerstone to creating powerful and intuitive user interfaces. 

The above-mentioned best practices will give you the confidence you need [to take React.js by its horns](https://www.liveedu.tv/guides/programming/react-js/) and escalate your front-end development skills to the next level.

What other React.js best practices do you know?

  
Please share your comments below.