How to Handle Loading, Error, Empty, and Success States :👈 👉:How to Refactor a Large React Component

How to Design Reusable React Components

How to Design Reusable React Components

1. Introduction

Reusable components are one of the most important concepts in React development.

Instead of writing the same UI code multiple times, we create a component once and reuse it in different parts of an application.

For example, an application may have several buttons:

  • Login button
  • Submit button
  • Cancel button
  • Save button
  • Delete button

Rather than creating separate button implementations, we can create one reusable Button component and customize it using props.

The main goal of reusable components is to reduce code duplication, improve consistency, and make applications easier to maintain.

2. What Is a Reusable Component?

A reusable component is a React component that can be used in multiple places with different data or configurations.

Example of a normal component:

function Welcome() {
    return <h2>Welcome to React</h2>;
}

We can reuse it multiple times:

function App() {
    return (
        <div>
            <Welcome />
            <Welcome />
            <Welcome />
        </div>
    );
}

However, this component always displays the same content.

We can make it more reusable by accepting props.

function Welcome({ name }) {
    return <h2>Welcome, {name}</h2>;
}
function App() {
    return (
        <div>
            <Welcome name="John" />
            <Welcome name="David" />
            <Welcome name="Sarah" />
        </div>
    );
}

Output:

Welcome, John
Welcome, David
Welcome, Sarah

The same component displays different content based on the supplied props.

3. Why Do We Need Reusable Components?

Consider an application with 20 pages. Every page contains a similar button.

Without reusable components:

  • Each page may have its own button implementation.
  • Updating button styles requires changing multiple files.
  • Different pages may display inconsistent buttons.
  • Code duplication increases.

With reusable components:

  • Create the button once.
  • Use it across multiple pages.
  • Change the implementation in one place.
  • Maintain consistent UI behavior.

Key Benefits

  1. Code reusability: Write once and use in multiple places.
  2. Maintainability: Changes can be made centrally.
  3. Consistency: Common UI elements behave and look consistently.
  4. Testability: Components can be tested independently.
  5. Readability: Large pages can be divided into smaller components.
  6. Scalability: New features can use existing components.

4. Design a Reusable Button Component

Let's start with a simple button.

Without Reusable Component

function Login() {
    return (
        <button>Login</button>
    );
}
function Save() {
    return (
        <button>Save</button>
    );
}
function Cancel() {
    return (
        <button>Cancel</button>
    );
}

The button markup is repeated.

With Reusable Component

function Button({ children, onClick }) {
    return (
        <button onClick={onClick}>
            {children}
        </button>
    );
}

Now we can use the same component:

function App() {
    return (
        <div>
            <Button onClick={() => alert("Login")}>
                Login
            </Button>
            <Button onClick={() => alert("Save")}>
                Save
            </Button>
            <Button onClick={() => alert("Cancel")}>
                Cancel
            </Button>
        </div>
    );
}

Here:

  • children represents the content placed between the opening and closing component tags.
  • onClick is a function passed from the parent.
  • The button implementation is shared.

5. Make Components Configurable Using Props

A good reusable component should support different configurations without requiring changes to its internal implementation.

For example, a button may need:

  • Different labels.
  • Different variants.
  • Different sizes.
  • Disabled state.
  • Loading state.
  • Click handling.

Example:

function Button({
    children,
    variant = "primary",
    size = "medium",
    disabled = false,
    onClick
}) {
    return (
        <button
            className={`btn btn-${variant} btn-${size}`}
            disabled={disabled}
            onClick={onClick}
        >
            {children}
        </button>
    );
}

Usage:

<Button variant="primary">
    Save
</Button>
<Button variant="secondary">
    Cancel
</Button>
<Button variant="danger">
    Delete
</Button>
<Button size="small">
    Edit
</Button>
<Button disabled>
    Submit
</Button>

The same component supports different requirements through props.

6. Use Composition Instead of Adding Too Many Props

One common mistake is creating a component with too many props to handle every possible UI requirement.

For example:

function Card({
    title,
    description,
    image,
    showButton,
    buttonText,
    showFooter,
    footerText,
    showIcon,
    icon,
    showHeader
}) {
    // Complex implementation
}

As more requirements are added, the component becomes difficult to maintain.

A better approach is component composition.

Composition means building a larger component by combining smaller components.

Example:

function Card({ children }) {
    return (
        <div className="card">
            {children}
        </div>
    );
}
function CardHeader({ children }) {
    return <div className="card-header">{children}</div>;
}
function CardBody({ children }) {
    return <div className="card-body">{children}</div>;
}
function CardFooter({ children }) {
    return <div className="card-footer">{children}</div>;
}

Usage:

function ProductCard() {
    return (
        <Card>
            <CardHeader>
                <h3>Laptop</h3>
            </CardHeader>
            <CardBody>
                <p>High-performance laptop.</p>
            </CardBody>
            <CardFooter>
                <button>Buy Now</button>
            </CardFooter>
        </Card>
    );
}

Another page can reuse the same components with different content:

function UserCard() {
    return (
        <Card>
            <CardHeader>
                <h3>John</h3>
            </CardHeader>
            <CardBody>
                <p>Software Developer</p>
            </CardBody>
            <CardFooter>
                <button>View Profile</button>
            </CardFooter>
        </Card>
    );
}

When to use composition:

  • Components have different content structures.
  • A component needs optional sections.
  • Too many Boolean props are making the component difficult to understand.
  • Consumers need control over the layout.

7. Build Reusable Components for Data Display

Consider an application that displays products, users, and orders.

All three may use a similar card layout.

Instead of creating three independent card implementations, we can create a reusable component.

function InfoCard({ title, description, children }) {
    return (
        <div className="info-card">
            <h3>{title}</h3>
            <p>{description}</p>
            {children}
        </div>
    );
}

Usage:

function Product() {
    return (
        <InfoCard
            title="Laptop"
            description="High-performance laptop"
        >
            <p>Price: ₹60,000</p>
            <button>View Product</button>
        </InfoCard>
    );
}
function User() {
    return (
        <InfoCard
            title="John"
            description="Software Developer"
        >
            <p>Experience: 5 years</p>
            <button>View Profile</button>
        </InfoCard>
    );
}
function Order() {
    return (
        <InfoCard
            title="Order #101"
            description="Order information"
        >
            <p>Status: Delivered</p>
            <button>View Order</button>
        </InfoCard>
    );
}

The common layout is reused, while each component supplies its own content.

8. Separate Reusable UI Components from Business Logic

A reusable component should generally focus on one clear responsibility.

For example, a UserList component should display users. It does not necessarily need to know how users are fetched from the API.

A good structure:

src/
│
├── components/
│   ├── Button.jsx
│   ├── Card.jsx
│   ├── Loading.jsx
│   └── ErrorMessage.jsx
│
├── features/
│   └── users/
│       ├── UserList.jsx
│       ├── UserCard.jsx
│       └── useUsers.js
│
├── services/
│   └── userService.js
│
└── App.jsx

Responsibilities:

File Responsibility
Button.jsxReusable button UI
Card.jsxCommon card layout
Loading.jsxLoading indicator
ErrorMessage.jsxError display
UserList.jsxDisplay a list of users
UserCard.jsxDisplay an individual user
useUsers.jsManage user-related data and behavior
userService.jsCommunicate with the users API

This separation makes the application easier to understand and maintain.

9. Reusable Components with TypeScript

In larger applications, TypeScript helps define which props a reusable component accepts.

Example:

type ButtonProps = {
    children: React.ReactNode;
    variant?: "primary" | "secondary" | "danger";
    disabled?: boolean;
    onClick?: () => void;
};
function Button({
    children,
    variant = "primary",
    disabled = false,
    onClick
}: ButtonProps) {
    return (
        <button
            className={`btn-${variant}`}
            disabled={disabled}
            onClick={onClick}
        >
            {children}
        </button>
    );
}

Usage:

<Button variant="primary">
    Save
</Button>
<Button variant="danger">
    Delete
</Button>

TypeScript provides:

  • Compile-time prop validation.
  • Better editor autocomplete.
  • Easier refactoring.
  • Improved documentation.
  • Fewer accidental incorrect prop values.

10. Avoid Over-Engineering Reusable Components

Not every piece of JSX needs to become a reusable component.

For example:

function WelcomeMessage() {
    return <h2>Welcome</h2>;
}

If this component is used only once and has no independent responsibility, extracting it may not provide much value.

Create reusable components when:

  • The same UI is used in multiple places.
  • The component represents a meaningful responsibility.
  • Different pages need the same behavior.
  • Independent testing or maintenance is useful.

Avoid creating components simply to reduce the number of lines in a file.

11. Common Mistakes to Avoid

  1. Too many props: Makes components difficult to understand and use.
  2. Excessive Boolean props: Consider composition when many combinations are possible.
  3. Duplicating business logic: Extract shared logic into custom Hooks or services where appropriate.
  4. Making components too generic: A component that handles unrelated requirements becomes difficult to maintain.
  5. Ignoring prop validation: Use TypeScript or suitable runtime validation where appropriate.
  6. Mutating props: Props are read-only; create new values instead.
  7. Unnecessary component extraction: Avoid creating components without a clear responsibility.
  8. Mixing API logic with presentation: Separate data fetching from UI when it improves clarity and reuse.
  9. Ignoring accessibility: Reusable components should support accessible labels, keyboard interaction, and semantic HTML.
  10. Unstable component definitions: Avoid defining component types inside another component when doing so causes them to be recreated on every render.

12. Best Practices

  • Follow the single-responsibility principle.
  • Use props to configure reusable components.
  • Use children for flexible content.
  • Prefer composition over excessive configuration props.
  • Keep components focused and understandable.
  • Separate UI, business logic, and API communication where appropriate.
  • Use TypeScript for well-defined component interfaces.
  • Provide sensible default prop values.
  • Support accessibility and keyboard interaction.
  • Avoid premature abstraction.
  • Reuse components when the shared behavior or structure is meaningful.
  • Keep component APIs simple and predictable.

13. Real-World Example: E-Commerce Application

Consider an e-commerce application with the following pages:

  • Home page.
  • Product listing page.
  • Product details page.
  • Shopping cart page.
  • Checkout page.

Several UI components may be shared across these pages.

E-Commerce Application
│
├── Common Components
│   ├── Button
│   ├── Card
│   ├── Header
│   ├── Footer
│   ├── Modal
│   └── Loading
│
├── Product Components
│   ├── ProductCard
│   ├── ProductList
│   └── ProductDetails
│
├── Cart Components
│   ├── CartItem
│   └── CartSummary
│
└── Checkout Components
    ├── AddressForm
    └── PaymentSummary

For example, the same Button component can be used for:

  • Add to Cart.
  • Buy Now.
  • Continue Shopping.
  • Place Order.
  • Cancel.

The same Card component can be used for products, order summaries, and user information.

This creates a consistent application and reduces duplicated code.

14. Reusable Component vs Custom Hook vs Utility Function

These concepts are related but solve different problems.

Concept Purpose Example
Reusable Component Reuse UI and interaction Button, Card, Modal
Custom Hook Reuse React stateful logic useUsers, useAuth
Utility Function Reuse ordinary JavaScript logic formatDate, calculateTotal
Service Encapsulate external communication userService, productService

Example:

// Utility function
function formatPrice(price) {
    return `₹${price.toLocaleString("en-IN")}`;
}
// Custom Hook
function useUsers() {
    // Shared user-related React logic
}
// Reusable Component
function Button({ children }) {
    return <button>{children}</button>;
}

Use the appropriate abstraction instead of putting everything into a component.

15. Interview Questions and Answers

Q1. What are reusable components in React?

Reusable components are components that can be used in multiple parts of an application with different data or configurations. They reduce code duplication and improve maintainability.

Q2. How do you make a React component reusable?

We can accept props, use default values, support children, and separate component responsibilities. This allows the same component to work with different data and requirements.

Q3. What is the role of props in reusable components?

Props allow parent components to pass data and configuration to child components. They make components configurable without changing their internal implementation.

Q4. What is component composition?

Component composition means building complex UI by combining smaller components. It provides flexibility without requiring a large number of configuration props.

Q5. What is the difference between a reusable component and a custom Hook?

A reusable component shares UI and behavior, whereas a custom Hook shares React logic such as state management and effects.

Q6. Should every React component be reusable?

No. Components should be extracted when they have a meaningful responsibility or when reuse provides a real benefit. Premature abstraction can make an application unnecessarily complex.

Q7. How do you avoid creating components with too many props?

Use component composition, children, smaller focused components, and custom Hooks where appropriate.

Q8. How does TypeScript help with reusable components?

TypeScript defines the expected prop types, improves autocomplete, catches incorrect values during development, and makes component APIs easier to understand.

Q9. Does creating reusable components automatically improve React performance?

No. Reusability primarily improves code organization and maintainability. Performance depends on rendering behavior, state management, component structure, and other factors. Techniques such as React.memo may help in suitable situations.

Q10. What is the difference between a generic component and a reusable component?

A reusable component is designed to be used in multiple places. A generic component is designed to work with different types of data or content. A component can be both reusable and generic.

16. Final Takeaway

Designing reusable React components is about creating small, focused, configurable building blocks that can be combined to build larger applications.

Remember these important principles:

  • Use props to pass data and configuration.
  • Use children to support flexible content.
  • Prefer composition when components need different structures.
  • Separate UI from reusable logic and API communication.
  • Avoid unnecessary abstractions and excessive props.

A good reusable component should be easy to understand, easy to configure, and easy to use in different parts of an application.

🔙
How to Handle Loading, Error, Empty, and Success States :👈 👉:How to Refactor a Large React Component

Comments and Discussion