0
0
ReactHow-ToBeginner · 3 min read

How to Create Reusable Components in React Easily

To create a reusable component in React, define a function component that accepts props to customize its behavior or appearance. Use this component multiple times by passing different props, making your UI code cleaner and easier to maintain.
📐

Syntax

A reusable React component is a function that returns JSX and accepts props as input. props are like parameters that let you customize the component each time you use it.

Example parts:

  • function ComponentName(props) { ... }: Defines the component.
  • return ( ... ): Returns the UI structure.
  • props.propertyName: Accesses passed-in values.
jsx
function Button(props) {
  return <button>{props.label}</button>;
}
Output
<button>label text</button>
💻

Example

This example shows a reusable Button component that changes its label based on the label prop. You can use it multiple times with different labels.

jsx
import React from 'react';

function Button(props) {
  return <button>{props.label}</button>;
}

export default function App() {
  return (
    <div>
      <Button label="Save" />
      <Button label="Cancel" />
      <Button label="Delete" />
    </div>
  );
}
Output
<button>Save</button> <button>Cancel</button> <button>Delete</button>
⚠️

Common Pitfalls

Common mistakes when creating reusable components include:

  • Not using props to customize the component, making it inflexible.
  • Hardcoding values inside the component instead of passing them as props.
  • Forgetting to pass required props, causing empty or broken UI.

Always design components to accept props for flexibility.

jsx
/* Wrong: hardcoded label, not reusable */
function Button() {
  return <button>Click me</button>;
}

/* Right: label passed as prop */
function Button(props) {
  return <button>{props.label}</button>;
}
📊

Quick Reference

  • Define components as functions that accept props.
  • Use props to customize content or behavior.
  • Reuse components by rendering them with different props.
  • Keep components focused on one task for easier reuse.

Key Takeaways

Create reusable components as functions that accept props for customization.
Use props to pass different data to the same component for flexibility.
Avoid hardcoding values inside components to keep them reusable.
Reuse components by rendering them multiple times with different props.
Keep components simple and focused to maximize reuse.