ReactMedium

Folder structure best practice?

Organize by feature (domain) rather than by file type once an app grows: each feature folder holds its components, hooks, API calls, types and tests, while truly shared pieces live in components/ui, hooks and lib. Keep imports flowing from app to features to shared code, and let your framework's routing conventions shape the top level.

Feature-based layout (recommended for medium and large apps)

src/
  app/            routes, providers, app shell
  features/
    auth/         components, hooks, api.ts, types.ts, tests
    cart/
    products/
  components/ui/  shared design-system components (Button, Modal)
  hooks/          shared generic hooks
  lib/            api client, utils, config
  types/

Type-based layout (fine for small apps)

components/, hooks/, pages/, services/, utils/. It becomes hard to navigate as files multiply.

Principles

  • Colocation: keep things close to where they are used; move them to shared folders only when reused.
  • Unidirectional imports: shared code never imports from features; features avoid importing each other's internals (expose a small index.ts public API if needed). Tools like eslint-plugin-boundaries enforce this.
  • Consistent naming: kebab-case files, one component per file for significant components.
  • Tests next to code: cart-summary.test.tsx beside cart-summary.tsx.
  • Avoid deep nesting beyond three or four levels.
  • Path aliases (@/features/cart) instead of ../../../.

Frameworks

Next.js (app/ routes) and React Router framework mode (app/routes/) define the routing layer; keep feature code in features/ or colocated _components folders.

Code example

tsx
1// src/features/cart/
2// ├── components/cart-summary.tsx
3// ├── components/cart-item.tsx
4// ├── hooks/use-cart.ts
5// ├── api.ts
6// ├── types.ts
7// ├── cart-summary.test.tsx
8// └── index.ts <- public API of the feature
9
10// src/features/cart/index.ts
11export { CartSummary } from "./components/cart-summary";
12export { useCart } from "./hooks/use-cart";
13export type { CartItem } from "./types";
14
15// src/app/checkout-page.tsx
16// import { CartSummary, useCart } from "@/features/cart"; // import via the public API
17// import { Button } from "@/components/ui/button"; // shared UI
18// import { formatPrice } from "@/lib/format"; // shared utils
19
20// tsconfig.json
21// { "compilerOptions": { "paths": { "@/*": ["./src/*"] } } }

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app