DEV Community

Cover image for 3 Best Practices for Working With React Components
Dr. Michael Garbade
Dr. Michael Garbade

Posted on • Originally published at blog.liveedu.tv

3 Best Practices for Working With React Components

(This article was originally published on our blog here ).

React.js (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 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:

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:

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

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 <button> 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 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.

Top comments (4)

Collapse
 
chimon1984 profile image
Ryan Edge

One of the core tenants of component driven design is the single responsibility principle so that might be worth mentioning when considering how and when to break up components.

Collapse
 
educationecosystem profile image
Dr. Michael Garbade

True, thanks for mentioning that!

Collapse
 
jglasovic profile image
jglasovic

In the third example, you create a functional component named Liveedu and then in App component you use a component named Button. Small mistake but everything else is explained perfectly :))

Collapse
 
educationecosystem profile image
Dr. Michael Garbade

Thanks for seeing that!