3 Best Practices for Working With React Components

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

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

Dr. Michael J. Garbade

I, Dr. Michael J. Garbade is the co-founder of the Education Ecosystem (aka LiveEdu), ex-Amazon, GE, Rebate Networks, Y-combinator. Python, Django, and DevOps Engineer. Serial Entrepreneur. Experienced in raising venture funding. I speak English and German as mother tongues. I have a Masters in Business Administration and Physics, and a Ph.D. in Venture Capital Financing. Currently, I am the Project Lead on the community project -Nationalcoronalvirus Hotline I write subject matter expert technical and business articles in leading blogs like Opensource.com, Dzone.com, Cybrary, Businessinsider, Entrepreneur.com, TechinAsia, Coindesk, and Cointelegraph. I am a frequent speaker and panelist at tech and blockchain conferences around the globe. I serve as a start-up mentor at Axel Springer Accelerator, NY Edtech Accelerator, Seedstars, and Learnlaunch Accelerator. I love hackathons and often serve as a technical judge on hackathon panels.

View Comments

Recent Posts

Blockchain in Elections: A Leap Toward Transparent Democracy

In 2024 we're witnessing a critical point in democratic technology: the integration of blockchain and…

3 weeks ago

Win Big with Our Amazon Fire Max 11 & AirPods Pro Giveaway!

We’re thrilled to announce an exciting opportunity for you to win not one but two…

2 months ago

Unleashing Potential: How Education Ecosystem Transforms Learning into Real-World Success

Acquiring practical skills is crucial for career advancement and personal growth. Education Ecosystem stands out…

4 months ago

The Role of Artificial Intelligence in Modern Software Development

Artificial Intelligence (AI) has been making significant strides in various industries, and the software development…

7 months ago

Highest Stable Coin Yields – (W16 – 2024)

Another week to bring you the top yield platforms for three of the most prominent…

8 months ago

LEDU Token OTC Trading

If you hold a large volume of LEDU tokens above 1 million units and wish…

9 months ago