How to be Better in React Code Reusability - Part 1

March 16, 2023

How to be Better in React Code Reusability - Part 1

A Brief Overview of React and Its Popularity

React is one of the most popular front-end JavaScript libraries for building user interfaces. Developed by Meta (formerly Facebook), React has gained a massive following in the web development community due to its simplicity, flexibility, and scalability.

React's popularity stems from its component-based architecture, which allows developers to break down complex user interfaces into small, reusable React components. These smaller components can then be composed to create larger, more complex UIs—a core React design pattern that powers modern web applications.

However, as React applications grow, managing the codebase becomes challenging. This is where code reusability in React comes in—writing reusable components that can be shared across different parts of an application (and even across multiple projects). It saves time, reduces errors, and improves scalability and maintainability.

In this React tutorial, we'll explore how to create reusable React components, the importance of DRY (Don't Repeat Yourself) principles, and React best practices for component design.


React Components and Their Importance in Reusability

Components are the building blocks of React. When designed for reusability, they can be imported and integrated across different parts of an app, speeding up development and reducing duplication.

Comparison: Functional vs. Class Components

Functional Components

  • Simpler, concise, easier to test and maintain.
  • Take props as input and return JSX.
  • Commonly used with hooks for state and lifecycle logic.
  • Ideal for stateless UI pieces or logic that can be wrapped in custom hooks.

Example:

function Welcome(props) {
  return <h1>Hello, {props.name}!</h1>;
}

This Welcome component can be reused anywhere in the app with different name props.


Class Components

  • More powerful, with state and lifecycle methods.
  • Verbose and harder to maintain but useful in certain scenarios.

Example:

class Timer extends React.Component {
  constructor(props) {
    super(props);
    this.state = { seconds: props.seconds };
  }

  tick() {
    this.setState((state) => ({
      seconds: state.seconds - 1,
    }));
  }

  componentDidMount() {
    this.interval = setInterval(() => this.tick(), 1000);
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  render() {
    return <div>Seconds remaining: {this.state.seconds}</div>;
  }
}

The timer is reusable by simply passing different seconds props.


Examples of Reusable Components in React

1. Button Component

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

2. Modal Component

function Modal(props) {
  return (
    <div className="modal">
      <div className="modal-content">{props.children}</div>
    </div>
  );
}

3. Form Input Component

function FormInput(props) {
  return (
    <div>
      <label>{props.label}</label>
      <input type={props.type} value={props.value} onChange={props.onChange} />
    </div>
  );
}

React Best Practices for Code Reusability

Following these React component patterns ensures your code stays maintainable and scalable.

1. Master Props and State

  • Use React props for component customization and configuration
  • Use React state (with useState hook) for managing dynamic behavior
  • Combine both for flexible, reusable UI components

2. Higher-Order Components (HOCs)

HOCs wrap components with additional functionality.
Example – Authentication:

function withAuth(WrappedComponent) {
  return class extends React.Component {
    state = { isAuthenticated: false };

    componentDidMount() {
      const isAuthenticated = true; // Replace with real check
      this.setState({ isAuthenticated });
    }

    render() {
      return this.state.isAuthenticated ? <WrappedComponent {...this.props} /> : null;
    }
  };
}

3. Render Props

Render props let you share logic between components by passing a function.

Example:

class Mouse extends React.Component {
  state = { x: 0, y: 0 };

  handleMouseMove = (event) => {
    this.setState({ x: event.clientX, y: event.clientY });
  };

  render() {
    return <div onMouseMove={this.handleMouseMove}>{this.props.render(this.state)}</div>;
  }
}

Usage:

<Mouse render={({ x, y }) => <p>Mouse position: {x}, {y}</p>} />

Conclusion

Code reusability is a key factor in scalable React development. By leveraging:

  • Functional components with React Hooks
  • Higher-order components (HOCs) for cross-cutting concerns
  • Render props for flexible component composition

…developers can build flexible, maintainable, and modular React applications.

Reusable React components improve productivity, ensure UI consistency, and enhance long-term maintainability. Whether you're building a React single-page application (SPA), a Next.js project, or a React Native mobile app, these patterns form the foundation of professional React development.

In Part 2, we'll explore custom hooks and modern patterns like compound components and the children prop pattern.