Sub topic 4
Building feature modules
This chapter assumes you can write React components and hooks, read TypeScript, and use import and export. It also assumes you have worked in a small or medium React app built with Vite or webpack. Earlier chapters compared organizing by file type with organizing by feature. Here you build a feature module.
What a feature module is
A feature module is a folder that holds everything for one user-facing capability, such as a cart, an order history, or a settings area. Components, hooks, API calls, types, and tests all sit together. The folder exposes a small set of names to the rest of the app and hides the rest.
Two properties define a feature module:
- Cohesion. Files that change together live together. Adding a "remove item" button to the cart touches only
features/cart. - A narrow surface. Other code uses the feature through one entry file,
index.ts. Everything else in the folder is private.
Without the second property you only have a folder. Anyone can import features/cart/hooks/useCart from anywhere, and the folder structure stops meaning anything.
The anatomy of one feature
Here is the layout used throughout this tutorial.
src/
app/
App.tsx
routes.tsx
features/
cart/
components/
CartList.tsx
CartList.test.tsx
hooks/
useCart.ts
api.ts
index.ts
orders/
components/
hooks/
api.ts
index.ts
shared/
ui/
Button.tsx
lib/
formatDate.tsEach top-level folder has one job.
| Folder | Contains | May import from |
|---|---|---|
| `app/` | Root component, providers, route table | `features/`, `shared/` |
| `features/<name>/` | One capability, end to end | `shared/`, other features' `index.ts` only |
| `shared/` | Generic UI and utilities with no business knowledge | Other `shared/` code only |
Dependencies point one way: app depends on features, features depend on shared, and shared depends on nothing above it. shared/ knows nothing about carts or orders.
Building the cart feature step by step
1. Start with types and the API
Define the data shape first. Other layers depend on it.
// src/features/cart/types.ts
export type CartItem = {
id: string;
name: string;
quantity: number;
unitPrice: number;
};The index.ts shown below re-exports CartItem from ./types, so this file belongs in the feature folder next to api.ts.
2. Write the hook that components will use
Keep component bodies small by putting state and logic in a hook inside the feature. This chapter only places the hook. A later chapter covers hook design.
// src/features/cart/hooks/useCart.ts
import { useCallback, useState } from "react";
import type { CartItem } from "../types";
export function useCart(initialItems: CartItem[] = []) {
const [items, setItems] = useState<CartItem[]>(initialItems);
const removeItem = useCallback((id: string) => {
setItems((current) => current.filter((item) => item.id !== id));
}, []);
const total = items.reduce(
(sum, item) => sum + item.quantity * item.unitPrice,
0,
);
return { items, total, removeItem };
}Inside the feature, files use relative imports such as ../types. Relative paths are fine within one feature because the files move together.
3. Build the component
// src/features/cart/components/CartList.tsx
import { Button } from "@/shared/ui/Button";
import { useCart } from "../hooks/useCart";
import type { CartItem } from "../types";
export function CartList({ initialItems }: { initialItems: CartItem[] }) {
const { items, total, removeItem } = useCart(initialItems);
return (
<section>
<ul>
{items.map((item) => (
<li key={item.id}>
{item.name} × {item.quantity}
<Button onClick={() => removeItem(item.id)}>Remove</Button>
</li>
))}
</ul>
<p>Total: {total.toFixed(2)}</p>
</section>
);
}The feature imports Button from shared/ui through an alias. It imports its own hook with a relative path. That split is deliberate: aliases cross module boundaries, and relative paths stay inside one.
4. Write the public API
// src/features/cart/index.ts
export { CartList } from "./components/CartList";
export { useCart } from "./hooks/useCart";
export type { CartItem } from "./types";This file is the contract. Code outside the feature writes import { CartList } from "@/features/cart". It never writes @/features/cart/components/CartList. You can rename, split, or rewrite anything behind the index without touching consumers, as long as the exports stay the same.
The @/ alias comes from a paths entry in tsconfig.json, and your bundler needs a matching alias setting. A later chapter covers the setup.
Deciding what to export
Export the smallest set that other code needs. A useful test is to ask who will import the name.
- Export the components a page renders, hooks other features legitimately need, and the types that appear in those signatures.
- Keep private helper components, internal hooks, API functions, and anything only used inside the folder.
If you export the API functions, other features start calling them directly. Later you can no longer change caching or request shape without checking every caller. Exposing a hook such as useCart leaves you free to change what is behind it.
Also watch the types you export. If useCart returns an internal type that you do not export, consumers can still use it through inference, but they cannot name it. Export types that appear in public signatures.
Where each kind of code goes
When you are unsure where a file belongs, apply these rules in order.
- If only one feature uses it, put it in that feature.
- If two features use it and it contains business knowledge (for example, "what counts as a discounted item"), do not move it to
shared/yet. Either keep it in the owning feature and export it, or merge the features if they are really one. - If it is generic, with no domain words in its name or props, it goes in
shared/.
Moving code into shared/ too early is the most common structural mistake. shared/ becomes a dumping ground, and every feature then depends on it. Wait until a second real use appears, then move it.
Common errors
Features importing each other in a cycle
If cart imports from orders and orders imports from cart, the two features cannot be understood or tested alone. Bundlers may also give you undefined at import time when modules load in an unlucky order. Fix a cycle in one of three ways:
- Move the shared piece down to
shared/, if it is generic. - Pass the needed data or callback in as a prop, so the feature does not import the other one.
- Combine the two features if they are always changed together.
Barrel files that re-export everything
An index.ts that does export * from "./components/CartList" for every file turns the whole folder into the public API. It also makes it easy to leak internals by accident. List exports by name.
Circular imports inside a feature
A component that imports from its own index.ts creates a loop, because the index imports the component. Inside a feature, import the specific file with a relative path. Reserve the index for code outside the feature.
Using the index for a heavy feature and losing lazy loading
If a page-sized feature is loaded with React.lazy, importing its index from many places can pull its code into the main bundle. For route-level features, the route file should be the only place that references it, through a dynamic import(). A later chapter on code splitting covers this.
Testing and moving a feature
Tests sit next to the code they cover, as with CartList.test.tsx in the layout above. The tests move with the feature if you rename or delete it. Tests inside the feature can import internals freely. Tests outside it should use the public API only.
The feature layout also helps when you migrate an existing flat codebase. You can move one feature at a time into its own folder, add its index.ts, and fix the imports that point at it. The rest of the app keeps working in the meantime.
Summary of the working rules
- One folder per capability, with components, hooks, API code, types, and tests inside it.
- An
index.tsthat lists the public exports by name. - Relative imports inside a feature, aliased imports across features and from
shared/. - Dependencies that point one way:
app, then features, thenshared. - Generic code goes to
shared/only once a second real use exists.
Exercise
Your orders feature needs the CartItem type, and your cart feature needs to show an order count. Both features currently import each other's internal files. What do you change so the dependency is safe?
Show answer
First, make each feature export what the other needs from its index.ts (CartItem from cart, and a hook or component for the count from orders), and have the other feature import only from those index files. Then check for a cycle. A cycle exists here because each feature depends on the other. Break it by passing the count into the cart component as a prop from a page in app/, or by moving a generic piece to shared/. If the two features always change together, merge them into one.
Exercise
A teammate puts formatCartTotal in shared/lib because "other features might want it later". Is that the right place, and what would you do?
Show answer
No. The function has cart-specific meaning, and no second feature uses it yet. Keep it inside features/cart, and export it from index.ts only if another feature actually needs it. Move generic pieces, such as a plain formatCurrency, to shared/lib once a second real use exists.