---
name: react-enterprise-architect
description: React/Next.js enterprise architecture patterns cho GoodGo frontend apps. Use for project structure, component organization, data fetching, routing, và App Router patterns.
compatibility: "next>=16, react>=19, typescript>=5"
metadata:
  author: Velik Ho
  version: "1.0"
---

# React Enterprise Architect / Kiến Trúc React Enterprise

## When to Use This Skill / Khi Nào Sử Dụng

Use this skill when:
- Creating new frontend apps (web-client, web-admin, web-merchant...)
- Organizing feature modules / Tổ chức feature modules
- Setting up Next.js App Router / Thiết lập Next.js App Router
- Implementing data fetching patterns / Triển khai patterns fetch data
- Designing component hierarchies / Thiết kế cấu trúc component

## Core Principles / Nguyên Tắc Cốt Lõi

1. **Feature-Based Organization**: Group by feature, not by type
2. **Server-First**: Prefer Server Components, use Client Components sparingly
3. **Colocation**: Keep related code together
4. **Single Responsibility**: Each module has one clear purpose
5. **Type Safety**: TypeScript everywhere

## Project Structure / Cấu Trúc Dự Án

```
apps/web-{app}/
├── src/
│   ├── app/                    # Next.js App Router
│   │   ├── (routes)/           # Route groups
│   │   ├── api/                # API routes
│   │   ├── layout.tsx          # Root layout
│   │   └── page.tsx            # Home page
│   ├── features/               # Feature modules (CORE)
│   │   ├── auth/               # Authentication feature
│   │   ├── chat/               # Chat feature
│   │   ├── dashboard/          # Dashboard feature
│   │   └── shared/             # Shared components & utils
│   │       ├── components/     # Reusable components
│   │       ├── hooks/          # Custom hooks
│   │       ├── lib/            # Utilities
│   │       ├── types/          # Shared types
│   │       └── i18n/           # Internationalization
│   ├── stores/                 # Zustand stores
│   │   └── __tests__/          # Store tests
│   ├── services/               # API service clients
│   ├── providers/              # React context providers
│   ├── styles/                 # Global styles, theme
│   └── stories/                # Storybook stories (docs)
├── e2e/                        # Playwright E2E tests
├── public/                     # Static assets
└── .storybook/                 # Storybook config
```

## Key Patterns / Mẫu Chính

### Feature Module Structure

```
features/chat/
├── components/                 # Feature-specific components
│   ├── ChatInput.tsx
│   ├── ChatMessage.tsx
│   └── ChatSidebar.tsx
├── hooks/                      # Feature-specific hooks
│   └── useChat.ts
├── types/                      # Feature types
│   └── chat.types.ts
├── utils/                      # Feature utilities
│   └── formatMessage.ts
└── index.ts                    # Public exports (barrel file)
```

### Server vs Client Components

```tsx
// ✅ GOOD: Server Component (default)
// EN: No "use client" directive - renders on server
// VI: Không có "use client" - render trên server
async function ChatHistory({ userId }: { userId: string }) {
  const messages = await fetchMessages(userId); // Server-side fetch
  return <MessageList messages={messages} />;
}

// ✅ GOOD: Client Component (only when needed)
// EN: Add "use client" for interactivity
// VI: Thêm "use client" khi cần tương tác
'use client';

import { useState } from 'react';

function ChatInput() {
  const [message, setMessage] = useState('');
  return <input value={message} onChange={(e) => setMessage(e.target.value)} />;
}
```

### Data Fetching Pattern

```tsx
// EN: Server Component with async data fetching
// VI: Server Component với async data fetching
async function Dashboard() {
  // Direct fetch in Server Component
  const stats = await fetchStats();
  
  return (
    <div>
      <StatsCards data={stats} />
      {/* Client component for interactive chart */}
      <InteractiveChart initialData={stats} />
    </div>
  );
}
```

### Route Organization (App Router)

```
app/
├── (auth)/                     # Auth route group (no layout)
│   ├── login/page.tsx
│   └── register/page.tsx
├── (dashboard)/                # Dashboard route group with layout
│   ├── layout.tsx              # Shared dashboard layout
│   ├── page.tsx                # /dashboard
│   └── settings/page.tsx       # /dashboard/settings
├── layout.tsx                  # Root layout (providers, global UI)
├── loading.tsx                 # Global loading state
├── error.tsx                   # Global error boundary
└── not-found.tsx               # 404 page
```

### Barrel Exports (index.ts)

```typescript
// features/chat/index.ts
// EN: Export only public API, hide internal components
// VI: Chỉ export public API, ẩn internal components

export { ChatContainer } from './components/ChatContainer';
export { useChat } from './hooks/useChat';
export type { Message, ChatState } from './types/chat.types';

// ❌ DON'T export internal components
// export { ChatMessageBubble } from './components/internal/ChatMessageBubble';
```

## Common Mistakes / Lỗi Thường Gặp

### 1. Using Client Components Unnecessarily

```tsx
// ❌ BAD: Every component is client
'use client';
function Header() { return <h1>Title</h1>; }

// ✅ GOOD: Server Component (default)
function Header() { return <h1>Title</h1>; }
```

### 2. Mixing Feature Concerns

```tsx
// ❌ BAD: Chat component directly uses auth store
import { useAuthStore } from '@/stores/auth-store';

function ChatInput() {
  const user = useAuthStore(s => s.user); // Cross-feature dependency
}

// ✅ GOOD: Receive user as prop from parent
function ChatInput({ userId }: { userId: string }) {
  // Feature-isolated, receives data via props
}
```

### 3. Forgetting Loading/Error States

```tsx
// ✅ GOOD: Always handle loading and error
// app/chat/loading.tsx
export default function Loading() {
  return <ChatSkeleton />;
}

// app/chat/error.tsx
'use client';
export default function Error({ error, reset }: { error: Error; reset: () => void }) {
  return <ErrorMessage error={error} onRetry={reset} />;
}
```

## Quick Reference / Tham Chiếu Nhanh

| Concept | Pattern |
|---------|---------|
| Folder structure | Feature-based (`features/`) |
| Components location | `features/{name}/components/` |
| Shared components | `features/shared/components/` |
| Stores | `stores/{name}-store.ts` |
| API routes | `app/api/{resource}/route.ts` |
| Page routes | `app/(group)/page.tsx` |
| Layouts | `app/layout.tsx`, route `layout.tsx` |
| Loading states | `loading.tsx` per route |
| Error handling | `error.tsx` per route |

## Resources / Tài Nguyên

- [React State Management](../react-state-management/SKILL.md) - Zustand, TanStack Query patterns
- [React UI Components](../react-ui-components/SKILL.md) - Component development
- [React Testing Patterns](../react-testing-patterns/SKILL.md) - Testing strategies
- [Project Rules](../project-rules/SKILL.md) - GoodGo coding standards
- [Next.js App Router Docs](https://nextjs.org/docs/app)
