Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save tjunghans/defb4408cfc1eb7aeffeb0dda8960f9a to your computer and use it in GitHub Desktop.

Select an option

Save tjunghans/defb4408cfc1eb7aeffeb0dda8960f9a to your computer and use it in GitHub Desktop.
Vite + Vitest + TypeScript + React Component Structure Guidelines

Vite + Vitest + TypeScript + React Component Structure Guidelines

All source code lives under ./src.

1. Components Location

  • All React components are stored in ./src/components/.
  • Simple components:
    • Use a single file named after the component. Example: MyComponent.tsx exports the MyComponent component.
    • One exported component per .tsx file.

2. Complex Components

If a component grows large (e.g., requires scrolling to see the whole file), split it into smaller parts:

  • Create a folder under ./src/components/ named after the main component.
  • Inside, organize related code:
    • Subcomponents (SubComponent.tsx, AnotherSubComponent.tsx)
    • Custom hooks (my-component-custom-hook.ts)
    • Utilities (my-component-utils.ts)
    • Types (types.ts)
    • Tests (MyComponent.spec.tsx)
    • Mocks (mocks/ for Vitest/Jest mocks)
    • Barrel file (index.ts for simplified imports)

3. Barrel Files

  • Each complex component folder should have an index.ts exporting the main component and optionally related subcomponents.

  • This allows clean imports like:

    import { MyComponent } from "@/components";

4. Example Folder Structure

./src/components/MyComponent/
  __mocks__/                 # Vitest/Jest mocks
  MyComponent.tsx            # Main component
  MyComponent.spec.tsx       # Unit tests
  index.ts                   # Barrel exports
  SubComponent.tsx           # Related subcomponent
  AnotherSubComponent.tsx
  types.ts                   # Type definitions
  my-component-utils.ts      # Helper functions
  my-component-custom-hook.ts # Related custom hook

Tip: Keep components small and focused. A component file should ideally fit on one screen — if not, it’s time to break it down.

This pattern can be repeated for sub components as they start getting too large or complex.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment