Structuring Components

Keep components small, focused and organized for maintainability.

Good React apps grow from many small, well-named components. A few habits keep the codebase healthy.

Guidelines

  • One component per file, named the same as the file.
  • Keep a component focused on one responsibility; split it when it does too much.
  • Colocate related files — a component with its styles, tests and hooks.
  • Extract repeated logic into custom hooks and repeated UI into shared components.

Example

Example · javascript
// UserCard.jsx - one focused component per file
function UserCard({ user }) {
  return (
    <article>
      <h3>{user.name}</h3>
      <p>{user.email}</p>
    </article>
  );
}

export default UserCard;

When to use it

  • A growing SaaS codebase enforces one-component-per-file and a features/ folder structure so new engineers can locate, understand, and modify any component without a guide.
  • A code review checklist flags components over 200 lines as candidates for splitting, keeping each piece testable and its single responsibility clear.
  • A design token migration is simplified because every component is isolated in its own file, making global find-and-replace of className strings reliable.

More examples

One component per file

Keeps one component per file and names the file after the component for easy discoverability.

Example · jsx
// src/components/UserCard/UserCard.jsx
function UserCard({ name, email, avatarUrl }) {
  return (
    <div className="user-card">
      <img src={avatarUrl} alt={name} className="user-card__avatar" />
      <div className="user-card__info">
        <strong>{name}</strong>
        <span>{email}</span>
      </div>
    </div>
  );
}

export default UserCard;

Split large component into parts

Decomposes a large page component into three focused child components, each owning one responsibility.

Example · jsx
// BEFORE — one 300-line component doing too much
// AFTER — split into focused pieces

import OrderSummary from './OrderSummary';
import ShippingInfo from './ShippingInfo';
import PaymentSection from './PaymentSection';

function CheckoutPage() {
  return (
    <main>
      <OrderSummary />
      <ShippingInfo />
      <PaymentSection />
    </main>
  );
}

Co-locate related files

Co-locates the component, its tests, its styles, and a barrel export in one folder to keep related code together.

Example · bash
src/
  components/
    ProductCard/
      ProductCard.jsx     # component
      ProductCard.test.jsx # tests
      ProductCard.module.css # styles
      index.js            # re-export

Discussion

  • Be the first to comment on this lesson.