Sub topic 7
Layering pages, feature components, and shared UI
This chapter assumes you know the feature-folder layout from the earlier chapters: src/features/<name> with an index.ts public API, plus src/app and src/shared. It also assumes you are comfortable with React props, composition with children, and React Router. Here you will split components into three layers, learn which direction imports may flow, and see how to fix the usual violations.
Why layers
A feature folder tells you where code lives. It does not tell you what a component is allowed to know. Without a rule, a Button ends up importing cart types, a feature imports half of another feature, and a route file holds 300 lines of fetching and markup. Every component then depends on everything else, and a change in one place breaks code far away.
Layers add that rule. Each component belongs to one layer, and a layer may only depend on layers below it.
The three layers
| Layer | Location | Knows about | Typical content |
|---|---|---|---|
| Pages | `src/app/pages` | Routes, URL params, which features exist | Compose feature components into a screen, read route params, handle navigation |
| Feature components | `src/features/<name>/components` | One feature's domain, its hooks and API, shared UI | Cart list, order table, checkout form |
| Shared UI | `src/shared/ui` | Nothing about the business domain | Button, Modal, TextField, Spinner |
Pages are the top layer. Feature components sit in the middle. Shared UI is the foundation.
Two rules follow from this diagram:
- Imports go down, never up. Shared UI never imports from a feature, and a feature never imports from a page.
- Features do not import from each other. Sibling features are combined by a page, which is a layer above both.
Shared UI: domain-free building blocks
A shared component receives everything through props. It has no idea whether it sits in a cart or an invoice.
// src/shared/ui/Button.tsx
import type { ButtonHTMLAttributes } from "react";
type ButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & {
variant?: "primary" | "secondary";
};
export function Button({
variant = "primary",
className = "",
type = "button",
...rest
}: ButtonProps) {
return (
<button
type={type}
className={`btn btn-${variant} ${className}`.trim()}
{...rest}
/>
);
}The test for shared UI is simple. If you would have to rename the component or change its props to use it in an unrelated product, it is not shared UI. A Button passes. A <ButtonWithCartCount /> does not, so it belongs in the cart feature.
Feature components: domain logic, no routing
A feature component knows its domain. It can call the feature's hooks, use its types, and render shared UI. It should not read the URL or decide where the app navigates next.
// src/features/cart/components/CartSummary.tsx
import { Button } from "@/shared/ui/Button";
import { useCart } from "../hooks/useCart";
type CartSummaryProps = {
onCheckout: () => void;
};
export function CartSummary({ onCheckout }: CartSummaryProps) {
const { items, total } = useCart();
return (
<section>
<h2>Cart ({items.length})</h2>
<p>Total: ${total.toFixed(2)}</p>
<Button onClick={onCheckout} disabled={items.length === 0}>
Check out
</Button>
</section>
);
}CartSummary fetches and computes its own data through useCart. It does not call navigate. It exposes an onCheckout callback and lets the caller decide what happens. That keeps the component reusable in a drawer, a page, or a test.
Inside the feature, use relative imports (../hooks/useCart). Use the alias (@/shared/ui/Button) for anything that crosses a folder boundary at the top level.
Pages: composition and wiring
A page is the glue. It reads route parameters, picks feature components, and connects their callbacks to navigation. It should contain very little logic of its own.
// src/app/pages/CheckoutPage.tsx
import { useNavigate, useParams } from "react-router-dom";
import { CartSummary } from "@/features/cart";
import { OrderList } from "@/features/orders";
export function CheckoutPage() {
const { userId = "" } = useParams();
const navigate = useNavigate();
return (
<main>
<h1>Checkout</h1>
<CartSummary onCheckout={() => navigate(`/users/${userId}/confirmation`)} />
<OrderList userId={userId} />
</main>
);
}This page is where cart and orders meet. Neither feature knows the other exists. If you later remove the orders feature, you edit pages and nothing else.
// src/app/routes.tsx
import { Route, Routes } from "react-router-dom";
import { CheckoutPage } from "./pages/CheckoutPage";
export function AppRoutes() {
return (
<Routes>
<Route path="/users/:userId/checkout" element={<CheckoutPage />} />
</Routes>
);
}A useful size check: if a page grows past a screenful of JSX or contains useState for domain data, extract a feature component.
Letting features cooperate without importing each other
Sometimes one feature needs to show something owned by another. For example, the orders page might need a "Reorder" button that lives in the cart feature. There are three ways to handle this, and all keep the layer rule intact.
- Callbacks. The page passes a function that one feature calls and the other implements.
- Slots. A feature component accepts
childrenor a render prop, and the page fills the slot with another feature's component. - Lifting down. If two features truly share the same logic, move it to
shared/libor a new feature that both pages use.
// src/features/orders/components/OrderRow.tsx
import type { ReactNode } from "react";
import type { Order } from "../api";
type OrderRowProps = {
order: Order;
actions?: ReactNode;
};
export function OrderRow({ order, actions }: OrderRowProps) {
return (
<li>
Order {order.id}: ${order.total.toFixed(2)}
{actions}
</li>
);
}The actions slot lets a page drop a cart-owned button into an order row. OrderRow stays unaware of the cart.
Common errors
- Shared UI imports a feature. For example,
ModalimportsuseCartto show a badge. Fix this by passing the data as props, or by moving the component into the feature. - Feature imports another feature's internals. Imports like
@/features/orders/components/OrderRowbypass the public API and the layer rule. Compose in a page instead. - Business logic in pages. A page that filters orders, computes totals, and calls
fetchis a feature that never got a folder. Move that code into the feature. - Navigation inside feature components. Calling
useNavigatedeep in a feature ties it to one router setup and one URL scheme. Expose a callback instead. Reading a route param inside a feature is a softer case, but passing it as a prop is easier to test. sharedas a dumping ground. Moving a component tosharedbecause two features use it is premature. If both uses are domain-specific, the code probably belongs in one feature or a new one. Promote to shared only when the component has no domain knowledge.- Props that mirror the domain. A shared
Tablethat takesordersandonCancelOrderis a feature component in disguise. Give it genericrowsandcolumnsprops.
A placement checklist
When you create a new component, ask these questions in order:
- Does it read the URL, choose a route, or combine several features? It is a page.
- Does it use domain types, hooks, or API calls from one feature? It is a feature component in that feature.
- Could it be used unchanged in a product with different data? It is shared UI.
- Does it fit none of these because two features need the same domain logic? Create a new feature, or move the logic into a hook in
shared/libif it is generic.
Trade-offs
Layers cost a little indirection. Callbacks and slots add props, and a page sometimes forwards values that a deep import would have reached directly. In exchange, features can be moved, deleted, tested, and lazy loaded on their own. For a small app with one team, a strict three-layer rule may be more ceremony than it is worth. For a codebase with several teams, it is what keeps one team's change from breaking another's screen.
Exercise
Your Modal component in src/shared/ui imports useAuth from @/features/auth so it can hide a "Delete" button for read-only users. Which layer rule does this break, and how do you fix it?
Show answer
It breaks the rule that imports flow downward only, because shared UI depends on a feature. Remove the useAuth call from Modal. Make the delete button a slot, such as an actions prop or children, and have the caller (a feature component or page that may import useAuth) decide whether to render it. Modal then stays free of domain knowledge.
Exercise
A page needs to show a ProfileCard from the users feature next to an OrderList from the orders feature, and clicking a user's name inside ProfileCard should filter the orders. How can the two features cooperate without importing each other?
Show answer
Keep the filter state in the page. Pass ProfileCard an onSelectUser callback that updates it, and pass OrderList the selected user ID as a userId prop. The page combines the two features, and neither feature imports the other.