Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
110 changes: 110 additions & 0 deletions .agents/skills/feature-arch/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
---
name: feature-arch
description: Feature-based React folder structure and module boundaries.
---

# Feature-Based Architecture Best Practices

Comprehensive architecture guide for organizing React applications by features, enabling scalable development with independent teams. Contains 42 rules across 8 categories, prioritized by impact from critical (directory structure, imports) to incremental (naming conventions).

## When to Apply

Reference these guidelines when:
- Creating new features or modules
- Organizing project directory structure
- Setting up import rules and boundaries
- Implementing data fetching patterns
- Composing components from multiple features
- Reviewing code for architecture violations

## Rule Categories by Priority

| Priority | Category | Impact | Prefix |
|----------|----------|--------|--------|
| 1 | Directory Structure | CRITICAL | `struct-` |
| 2 | Import & Dependencies | CRITICAL | `import-` |
| 3 | Module Boundaries | HIGH | `bound-` |
| 4 | Data Fetching | HIGH | `fquery-` |
| 5 | Component Organization | MEDIUM-HIGH | `fcomp-` |
| 6 | State Management | MEDIUM | `fstate-` |
| 7 | Testing Strategy | MEDIUM | `test-` |
| 8 | Naming Conventions | LOW | `name-` |

## Quick Reference

### 1. Directory Structure (CRITICAL)

- `struct-feature-folders` - Organize by feature, not technical type
- `struct-feature-self-contained` - Make features self-contained
- `struct-shared-layer` - Use shared layer for truly generic code only
- `struct-flat-hierarchy` - Keep directory hierarchy flat
- `struct-optional-segments` - Include only necessary segments
- `struct-app-layer` - Separate app layer from features

### 2. Import & Dependencies (CRITICAL)

- `import-unidirectional-flow` - Enforce unidirectional import flow
- `import-no-cross-feature` - Prohibit cross-feature imports
- `import-public-api` - Export through public API only
- `import-avoid-barrel-files` - Avoid deep barrel file re-exports
- `import-path-aliases` - Use consistent path aliases
- `import-type-only` - Use type-only imports for types

### 3. Module Boundaries (HIGH)

- `bound-feature-isolation` - Enforce feature isolation
- `bound-interface-contracts` - Define explicit interface contracts
- `bound-feature-scoped-routing` - Scope routing to feature concerns
- `bound-minimize-shared-state` - Minimize shared state between features
- `bound-event-based-communication` - Use events for cross-feature communication
- `bound-feature-size` - Keep features appropriately sized

### 4. Data Fetching (HIGH)

- `fquery-single-responsibility` - Keep query functions single-purpose
- `fquery-colocate-with-feature` - Colocate data fetching with features
- `fquery-parallel-fetching` - Fetch independent data in parallel
- `fquery-avoid-n-plus-one` - Avoid N+1 query patterns
- `fquery-feature-scoped-keys` - Use feature-scoped query keys
- `fquery-server-component-fetching` - Fetch at server component level

### 5. Component Organization (MEDIUM-HIGH)

- `fcomp-single-responsibility` - Apply single responsibility to components
- `fcomp-composition-over-props` - Prefer composition over prop drilling
- `fcomp-container-presentational` - Separate container and presentational concerns
- `fcomp-props-as-data-boundary` - Use props as feature boundaries
- `fcomp-colocate-styles` - Colocate styles with components
- `fcomp-error-boundaries` - Use feature-level error boundaries

### 6. State Management (MEDIUM)

- `fstate-feature-scoped-stores` - Scope state stores to features
- `fstate-server-state-separation` - Separate server state from client state
- `fstate-lift-minimally` - Lift state only as high as necessary
- `fstate-context-sparingly` - Use context sparingly for feature state
- `fstate-reset-on-unmount` - Reset feature state on unmount

### 7. Testing Strategy (MEDIUM)

- `test-colocate-with-feature` - Colocate tests with features
- `test-feature-isolation` - Test features in isolation
- `test-shared-utilities` - Create feature-specific test utilities
- `test-integration-at-app-layer` - Write integration tests at app layer

### 8. Naming Conventions (LOW)

- `name-feature-naming` - Use domain-driven feature names
- `name-file-conventions` - Use consistent file naming conventions
- `name-descriptive-exports` - Use descriptive export names

## How to Use

Read `references/<rule-id>.md` for each rule above that matches the task: why it matters, then incorrect vs. correct code.

The layering and boundary rules align with Feature-Sliced Design (FSD), the most widely adopted React architecture standard; see [feature-sliced.design](https://feature-sliced.design/) for the full methodology.

## Related Skills

- For data fetching, see `tanstack-query` skill
- For React component patterns, see `react` skill
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
---
title: Use Events for Cross-Feature Communication
impact: MEDIUM-HIGH
impactDescription: Decouples features at runtime; enables loose coupling without direct imports
tags: bound, events, communication, decoupling
---

## Use Events for Cross-Feature Communication

When features must communicate without direct dependencies, use an event-based approach. This keeps features loosely coupled while allowing them to react to each other's actions.

**Incorrect (direct coupling):**

```typescript
// src/features/order/hooks/useOrder.ts
import { clearCart } from '@/features/cart/stores/cartStore';
import { showNotification } from '@/features/notification/stores/notificationStore';
import { sendAnalytics } from '@/features/analytics/utils/analytics';

export function useOrder() {
async function submitOrder(data: OrderData) {
const order = await createOrder(data);

// Directly calling into other features
clearCart();
showNotification({ type: 'success', message: 'Order placed!' });
sendAnalytics('order_completed', { orderId: order.id });
}
}
```

**Correct (event-based communication):**

```typescript
// src/shared/events/eventBus.ts
type EventMap = {
'order:completed': { orderId: string; total: number };
'order:failed': { error: string };
'user:logged-in': { userId: string };
'user:logged-out': void;
};

export const eventBus = createEventBus<EventMap>();

// src/features/order/hooks/useOrder.ts
import { eventBus } from '@/shared/events/eventBus';

export function useOrder() {
async function submitOrder(data: OrderData) {
const order = await createOrder(data);
eventBus.emit('order:completed', { orderId: order.id, total: order.total });
}
}

// src/features/cart/hooks/useCartSync.ts
import { eventBus } from '@/shared/events/eventBus';
import { useCartStore } from '../stores/cartStore';

export function useCartSync() {
useEffect(() => {
return eventBus.on('order:completed', () => {
useCartStore.getState().clearCart();
});
}, []);
}

// src/features/notification/hooks/useOrderNotifications.ts
import { eventBus } from '@/shared/events/eventBus';

export function useOrderNotifications() {
useEffect(() => {
return eventBus.on('order:completed', ({ orderId }) => {
showNotification({ type: 'success', message: `Order ${orderId} placed!` });
});
}, []);
}
```

**Benefits:**
- Order feature doesn't know about cart, notifications, or analytics
- New features can subscribe to events without modifying order
- Easy to test each feature in isolation

Reference: [Feature-Sliced Design](https://feature-sliced.design/)
88 changes: 88 additions & 0 deletions .agents/skills/feature-arch/references/bound-feature-isolation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
---
title: Enforce Feature Isolation
impact: HIGH
impactDescription: Changes in one feature have zero impact on others; enables fearless refactoring
tags: bound, isolation, coupling, independence
---

## Enforce Feature Isolation

Each feature should be modifiable, testable, and deployable without affecting other features. When features are isolated, refactoring is safe and localized. When they're coupled, every change risks cascading failures.

**Incorrect (coupled features):**

```typescript
// src/features/order/hooks/useOrder.ts
import { useCart } from '@/features/cart/hooks/useCart';
import { useUser } from '@/features/user/hooks/useUser';
import { usePayment } from '@/features/payment/hooks/usePayment';

export function useOrder() {
const cart = useCart();
const user = useUser();
const payment = usePayment();

// Tightly coupled to 3 other features
// Change in any feature can break orders
async function submitOrder() {
const order = {
items: cart.items,
userId: user.id,
paymentMethod: payment.selectedMethod,
};
// ...
}
}
```

**Correct (isolated with dependency injection):**

```typescript
// src/features/order/hooks/useOrder.ts
interface OrderDependencies {
items: CartItem[];
userId: string;
paymentMethod: PaymentMethod;
}

export function useOrder() {
async function submitOrder(deps: OrderDependencies) {
const order = {
items: deps.items,
userId: deps.userId,
paymentMethod: deps.paymentMethod,
};
// ...
}

return { submitOrder };
}

// src/app/pages/CheckoutPage.tsx - composition at app layer
import { useCart } from '@/features/cart';
import { useUser } from '@/features/user';
import { usePayment } from '@/features/payment';
import { useOrder } from '@/features/order';

export function CheckoutPage() {
const cart = useCart();
const user = useUser();
const payment = usePayment();
const order = useOrder();

const handleSubmit = () => {
order.submitOrder({
items: cart.items,
userId: user.id,
paymentMethod: payment.selectedMethod,
});
};
}
```

**Benefits:**
- Order feature can be tested with mock dependencies
- Cart, user, and payment can change without breaking orders
- Clear contract between features

Reference: [Feature-Sliced Design](https://feature-sliced.design/)
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
---
title: Scope Routing to Feature Concerns
impact: HIGH
impactDescription: Enables feature-level code splitting; prevents routing configuration sprawl
tags: bound, routing, scope, navigation
---

## Scope Routing to Feature Concerns

Route definitions belong in the app layer, but route parameters and navigation logic relevant to a feature can be encapsulated within that feature. This keeps routing concerns organized while maintaining the app layer's ownership of the route tree.

**Incorrect (routing logic scattered):**

```typescript
// src/features/user/components/UserProfile.tsx
import { useNavigate, useParams } from 'react-router-dom';

export function UserProfile() {
const navigate = useNavigate();
const { userId } = useParams(); // Feature assumes route structure

const goToSettings = () => {
navigate(`/users/${userId}/settings`); // Hardcoded route
};
}
```

**Correct (feature owns its route utilities):**

```typescript
// src/features/user/routes.ts
export const userRoutes = {
profile: (userId: string) => `/users/${userId}`,
settings: (userId: string) => `/users/${userId}/settings`,
orders: (userId: string) => `/users/${userId}/orders`,
} as const;

// src/features/user/hooks/useUserParams.ts
import { useParams } from 'react-router-dom';

export function useUserParams() {
const { userId } = useParams<{ userId: string }>();
if (!userId) throw new Error('userId is required');
return { userId };
}

// src/features/user/components/UserProfile.tsx
import { useNavigate } from 'react-router-dom';
import { userRoutes } from '../routes';
import { useUserParams } from '../hooks/useUserParams';

export function UserProfile() {
const navigate = useNavigate();
const { userId } = useUserParams();

const goToSettings = () => {
navigate(userRoutes.settings(userId)); // Uses feature's route builder
};
}

// src/app/routes/index.tsx
import { userRoutes } from '@/features/user';
import { UserProfile, UserSettings } from '@/features/user';

export const routes = [
{ path: userRoutes.profile(':userId'), element: <UserProfile /> },
{ path: userRoutes.settings(':userId'), element: <UserSettings /> },
];
```

**Benefits:**
- Route paths are centralized per feature
- Refactoring routes only requires changes in one place
- Type-safe route parameters

Reference: [Feature-Sliced Design](https://feature-sliced.design/)
Loading
Loading