Sub topic 2
Setting up path aliases
Assume you know React components, hooks, and import/export syntax. You should also know the basics of npm and a bundler such as Vite or webpack.
Setting up path aliases
A path alias is a short name for a directory. Instead of writing ../../../features/cart, use @/features/cart. This makes imports easier to read and reduces broken relative paths after files move.
TypeScript understands aliases through tsconfig.json:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
}
}The bundler must understand the same alias. With Vite, configure it explicitly:
// vite.config.ts
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import path from "node:path";
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
"@": path.resolve(__dirname, "src")
}
}
});Keep the TypeScript and bundler mappings identical. Otherwise the editor may accept an import that fails during development or production builds.
Public APIs and module boundaries
A feature should expose a small public API through its index.ts file:
// src/features/cart/index.ts
export { CartList } from "./components/CartList";
export { useCart } from "./hooks/useCart";
export type { CartItem } from "./types";Other features import from @/features/cart, not from @/features/cart/hooks/useCart. This boundary lets you reorganize internal files without changing every caller.
Component layers and custom hooks
Use separate layers for different responsibilities:
| Layer | Responsibility |
|---|---|
| Page | Connects routing and page-level composition |
| Feature | Implements one user-facing capability |
| Shared UI | Provides reusable visual primitives |
A custom hook is a function whose name starts with use and that packages reusable stateful logic. For example, useCart can coordinate cart state while CartList focuses on rendering.
flowchart TD
Page --> Feature
Feature --> Hook
Feature --> SharedUI
Hook --> Statecaption: Component and state relationships alt: A page uses a feature, which uses a custom hook and shared UI components; the hook manages state.
Deciding where state lives
Keep state in the smallest layer that needs it.
- Component state belongs in one component, such as an open menu.
- Feature state belongs in a feature, such as selected cart items.
- Shared server state belongs in a query cache or data layer when many screens use fetched data.
Moving state upward too early creates unnecessary dependencies. Moving it downward when several components need it causes duplicated state. Place it where the ownership and update rules remain clear.
Exercise
Where should a cart query used by several pages live?
Show answer
In the cart feature's data-access layer or shared server-state cache, exposed through a feature hook.