Moonstack

App Development
How to Build Reusable React Components-moonstack

What are Reusable React components: They can be compared to construction blocks. You may save time and effort by reusing these separate pieces of code throughout your website.

They could be anything from basic buttons to intricate shapes.

Why Use Reusable Components?

You may simply combine existing components to add new functionality as your website expands. Your code becomes more flexible and scalable as a result.

Reusable code allows you to reuse it in other projects without having to start from zero.

How to Make Reusable React Components

There are the two most important things to keep in mind when creating reusable React components:

1. Avoid Side Effects

Reusable components shouldn’t contain logic that communicates with external data (such as calling APIs). Rather, send this logic to the component as props.

For instance, a button may not be reusable if it performs a function other than merely being aesthetically pleasing, such as retrieving data from the internet.

This button component is reusable.  However, it is devoid of best practices.  In the example section, I’ll explain why.

// This is a reusable button component (bad practice!)
const Button = () => {
  return (
    <button> Click Me </button>
  );
}

2. Use Props

You can alter a component’s behavior and look by passing it props.  This enables you to use the same part for several tasks.

// This is a button component that can change its color
const Button = ({ color }) => {
  return (
    <button style={{ backgroundColor: color }}> Click Here </button>
  );
}

This is still a bad practice because “Click Here” is a fixed label.  Going back to the button component and changing the wording to, example, “Sign Up” is necessary.

This implies that we would have to go back and change the code each time you wanted to use a different text.  That is to say, it can no longer be reused.

Thinking about the solution?

You already know the solution.  However, I’ll demonstrate in the example section if you don’t.

Hint: Design the component to be flexible and adaptive by considering the various scenarios in which you might want to use it.

Examples of Reusable React Components

To help you started, here are some code samples and typical instances of reusable React components:

Buttons

Simple buttons with various designs and features.

// Button component
import React from "react";

const Button = ({ color, label, onClick }) => {
  return (
    <button
      className={`padding-2 shadow-none hover:shadow background-light-${color} hover:background-dark-${color}`}
      onClick={onClick}
    >
      {label}
    </button>
  );
};

export default Button;

// Using the Button component
<Button color="blue" label="Click Here" onClick={() => console.log("Button clicked!")} />

I did not write “Click Here” in the button component, as you can see.  My button doesn’t know anything about custom designs or messages because I want it to be reusable.

In order to alter them later without affecting the original button components, I passed them as props (color, label, and onClick).  I hope that clarifies it.

Solution: You need to pass each functionality as props in the reusable component.

Navbars

bars that allow you to navigate your website consistently.

// Navbar component
import React from "react";

const Navbar = ({ isLoggedIn }) => {
  return (
    <div className="navbar">
      <div className="navbar-container">
        <div className="navbar-logo">
          <img src={logo} alt="logo" />
        </div>
        <div className="navbar-links">
          <a href="/">Home</a>
          <a href="/about">About</a>
          <a href="/contact">Contact</a>
          {isLoggedIn ? (
            <a href="/profile">Profile</a>
          ) : (
            <a href="/login">Login</a>
          )}
        </div>
      </div>
    </div>
  );
};

export default Navbar;

// Using the Navbar component
<Navbar isLoggedIn={true} />

You can see, I passed <Navbar isLoggedIn={true} />

In order to indicate that the user is logged in, this line makes use of the Navbar component and passes the isLoggedIn prop with a value of true.  This will make the “Profile” link visible while concealing the “Login” link.

The Navbar component is reusable and allows props to alter its behavior, just like the button component.  Excellent!

Why It’s Not a Good Idea to Use API Calls in Button Components

You now have a thorough understanding of React’s reusable components.

Let’s solve a challenging problem to go further.

Take the case of having a button that initiates an API call.  The following could be the button component’s code:

import React from "react"; 
import doAPICall from "../api"

const SaveButton  = () => {
  return (
    <button
      onClick={() => {
        doAPICall();
      }}
    >
      Save
    </button>
  );
}

export default SaveButton

Since the button component above involves a side-effect (doAPICall()), it is obvious that you cannot utilize the button more than once.

This component can be made reusable.  The side-effect must first be extracted and passed as a prop to the button component in the manner shown below:

const App = () =>  {
  function doAPICall() {
    // Does an API call to save the current state of the app.
  }

  return (
    <div>
      <SaveButton onClick={doAPICall}/>
    </div>
  )
}

The button component should look like this:

const SaveButton  = ({
  onClick
}) => {
  return (
    <button
      onClick={onClick}
    >
      Save
    </button>
  );
}

As you can see, the button above can now be utilized again whenever you wish to save data by simply clicking on it.  Now, the button can be utilized in a variety of ways:

const App = () =>  {
  function saveUser() {
    // Does an API call to save the user.
  }

  function saveProject() {
    // Does an API call to save the project.
  }

  return (
    <div>
      <SaveButton onClick={saveUser}/>
      <SaveButton onClick={saveProject}/>
    </div>
  )
}

Additionally, you may increase the button component’s reusability by controlling the label with a prop:

const App = () =>  {
  function saveUser() {
    // Does an API call to save the user.
  }

  function saveProject() {
    // Does an API call to save the project.
  }

  return (
    <div>
      <SaveButton onClick={saveUser} label="Save user"  />
      <SaveButton onClick={saveProject} label="Save project" />
    </div>
  )
}

The button component should look like this:

const SaveButton  = ({
  onClick,
  label
}) => {
  return (
    <button
      onClick={onClick}
    >
      {label}
    </button>
  );
}

AI-Driven Cloud Platforms: How Automation Will Shape Cloud Computing in 2025

How to install React Compiler and ESLint plugin

Leave a comment

Your email address will not be published. Required fields are marked *

DROP US A LINE

Connect with Moonstack

Ready to take the first step towards unlocking opportunities, realizing goals, and embracing innovation? We're here and eager to connect.

image
To More Inquiry
+91 9772009900
image
To Send Mail
mail@moonstack.co

Your Success Starts Here!

      1/5
      • Choose your industry

      2/5
      • What service do you search for ?

      3/5
      • How much time you have for a development?

      4/5
      • What is project budget?

      Start your project with us now

      Let’s build the greatest experience for your customers

      5/5