React Patterns Reference
Target Spawn
Frontend domain work spawned via Agent(general-purpose) with frontend instructions - Applies these patterns directly to component design and state management.
Component Design Patterns
1. Compound Components
Parent and child share implicit state via Context.
Suited for: Tab, Accordion, Dropdown, Select
Structure: <Select> + <Select.Trigger> + <Select.Option>
2. Custom Hooks (Extraction Pattern)
Extract state logic into reusable hooks.
Suited for: Form management, API calls, localStorage, debounce
Naming: use prefix required - useForm, useDebounce, useAuth
3. Container/Presentational Separation
Separate data logic (Container) from UI (Presentational).
Suited for: Large apps, when testability is needed
Container: Data fetch, state management, event handlers
Presentational: Renders only from props, functionally pure
4. Headless Component
Provides behavior/state without UI.
Suited for: Design system-independent logic
Examples: headless useCombobox, useDialog, useTable
State Management Selection Guide
| State Type |
Tool |
Rationale |
| UI Local |
useState, useReducer |
Component-internal |
| Server State |
React Query / TanStack Query |
Caching, refetch, optimistic |
| Global Client |
Zustand |
Concise, minimal boilerplate |
| Complex Global |
Zustand + Immer |
Immutability convenience |
| URL State |
nuqs / useSearchParams |
Filters, pagination |
| Form State |
React Hook Form + Zod |
Integrated validation |
| Theme/i18n |
Context + Provider |
Low change frequency |
Decision Flow
Restorable from URL? -> URL state (nuqs)
Server data? -> React Query
Shared across components? -> Zustand
Component-internal? -> useState
Complex transitions? -> useReducer
Next.js App Router Structure
src/
├── app/ # App Router
│ ├── (auth)/ # Auth route group
│ │ ├── login/page.tsx
│ │ └── register/page.tsx
│ ├── (main)/ # Main route group
│ │ ├── dashboard/page.tsx
│ │ └── settings/page.tsx
│ ├── api/ # API Routes
│ ├── layout.tsx # Root layout
│ └── page.tsx # Home
├── components/
│ ├── ui/ # Base UI (Button, Input, Modal)
│ └── features/ # Feature components
│ ├── auth/
│ └── dashboard/
├── hooks/ # Custom hooks
├── lib/ # Utilities, config
├── stores/ # Zustand stores
├── types/ # TypeScript types
└── styles/ # Global styles
Component Quality Standards
| Item |
Standard |
| Component Size |
Under 200 lines (split if exceeded) |
| Props |
5 or fewer (group into object if exceeded) |
| Custom Hooks |
Always extract when reusing logic |
| Error Boundaries |
Set at the page level |
| Loading States |
Provide loading UI for all async ops |
| Form Validation |
Validate on both client and server |
Performance Patterns
| Pattern |
When |
Tool |
| Memoization |
Expensive computation |
useMemo, React.memo |
| Lazy Loading |
Bundle size |
React.lazy, next/dynamic |
| Virtualization |
1000+ item lists |
@tanstack/react-virtual |
| Image Optimization |
Image loading |
next/image |
| Optimistic Updates |
Immediate feedback |
React Query onMutate |
| Debounce |
Search, input |
useDeferredValue or custom hook |
Error Handling
Hierarchical Error Boundaries
RootErrorBoundary (global)
└── LayoutErrorBoundary (per section)
└── ComponentErrorFallback (individual)
API Error Handling
| HTTP Status |
Client Handling |
| 401 |
Auto logout + redirect |
| 403 |
Unauthorized UI |
| 404 |
Not Found page |
| 422 |
Per-field form error |
| 429 |
Retry + wait notice |
| 500 |
Generic error + retry button |
Accessibility Checklist
Common Rationalizations
| Rationalization |
Reality |
| "useEffect is fine for data fetching in React 19" |
React 19 provides use() and server components for data fetching. useEffect for fetch is a legacy pattern that causes waterfalls. |
| "Global state is simpler than prop drilling" |
Global state couples distant components. Prop drilling or composition via children is more predictable and testable. |
| "I will add TypeScript types later" |
Untyped components accumulate any-typed callers. Retrofitting types into a used component is much harder than starting typed. |
| "This component does not need memoization" |
Premature memoization is waste, but components rendering lists or expensive trees should be profiled, not assumed fast. |
| "CSS-in-JS is fine, everyone uses it" |
CSS-in-JS adds runtime overhead and bundle size. Tailwind or CSS Modules achieve the same scoping without the cost. |
Red Flags
- useEffect used for data fetching when server components or use() are available
- Component receives more than 5 props without decomposition or object grouping
- State management library used for server-cacheable data (use React Query or SWR instead)
- Inline styles or hardcoded pixel values instead of design tokens
- Component missing error boundary wrapping for async operations
Verification
1---
2name: moai-ref-react-patterns
3description: >
4 React/Next.js component design patterns, state management strategies, and project
5 structure reference for frontend development. Agent-extending skill that amplifies
6 frontend domain work (spawned via Agent(general-purpose) with frontend instructions)
7 with production-grade React patterns.
8 NOT for: backend API design, database modeling, DevOps, mobile apps.
9
10when_to_use: >
11 Use for React/Next.js component design patterns: state-management
12 strategies, hooks, component composition, and project structure.
13 Amplifies frontend domain work (Agent(general-purpose) with frontend
14 instructions) with production-grade React patterns.
15
16user-invocable: false
17metadata:
18 source: https://skillmd.com/skills/modu-ai/moai-ref-react-patterns
19 version: "1.0.0"
20 category: "domain"
21 status: "active"
22 updated: "2026-03-30"
23 tags: "react, nextjs, component, patterns, frontend, reference"
24
25# MoAI Extension: Progressive Disclosure
26progressive_disclosure:
27 enabled: true
28 level1_tokens: 100
29 level2_tokens: 3000
30---
31
32# React Patterns Reference
33
34## Target Spawn
35
36Frontend domain work spawned via `Agent(general-purpose)` with frontend instructions - Applies these patterns directly to component design and state management.
37
38## Component Design Patterns
39
40### 1. Compound Components
41Parent and child share implicit state via Context.
42
43Suited for: Tab, Accordion, Dropdown, Select
44Structure: `<Select>` + `<Select.Trigger>` + `<Select.Option>`
45
46### 2. Custom Hooks (Extraction Pattern)
47Extract state logic into reusable hooks.
48
49Suited for: Form management, API calls, localStorage, debounce
50Naming: `use` prefix required - `useForm`, `useDebounce`, `useAuth`
51
52### 3. Container/Presentational Separation
53Separate data logic (Container) from UI (Presentational).
54
55Suited for: Large apps, when testability is needed
56Container: Data fetch, state management, event handlers
57Presentational: Renders only from props, functionally pure
58
59### 4. Headless Component
60Provides behavior/state without UI.
61
62Suited for: Design system-independent logic
63Examples: headless `useCombobox`, `useDialog`, `useTable`
64
65## State Management Selection Guide
66
67| State Type | Tool | Rationale |
68|-----------|------|-----------|
69| UI Local | useState, useReducer | Component-internal |
70| Server State | React Query / TanStack Query | Caching, refetch, optimistic |
71| Global Client | Zustand | Concise, minimal boilerplate |
72| Complex Global | Zustand + Immer | Immutability convenience |
73| URL State | nuqs / useSearchParams | Filters, pagination |
74| Form State | React Hook Form + Zod | Integrated validation |
75| Theme/i18n | Context + Provider | Low change frequency |
76
77### Decision Flow
78```
79Restorable from URL? -> URL state (nuqs)
80Server data? -> React Query
81Shared across components? -> Zustand
82Component-internal? -> useState
83Complex transitions? -> useReducer
84```
85
86## Next.js App Router Structure
87
88```
89src/
90├── app/ # App Router
91│ ├── (auth)/ # Auth route group
92│ │ ├── login/page.tsx
93│ │ └── register/page.tsx
94│ ├── (main)/ # Main route group
95│ │ ├── dashboard/page.tsx
96│ │ └── settings/page.tsx
97│ ├── api/ # API Routes
98│ ├── layout.tsx # Root layout
99│ └── page.tsx # Home
100├── components/
101│ ├── ui/ # Base UI (Button, Input, Modal)
102│ └── features/ # Feature components
103│ ├── auth/
104│ └── dashboard/
105├── hooks/ # Custom hooks
106├── lib/ # Utilities, config
107├── stores/ # Zustand stores
108├── types/ # TypeScript types
109└── styles/ # Global styles
110```
111
112## Component Quality Standards
113
114| Item | Standard |
115|------|----------|
116| Component Size | Under 200 lines (split if exceeded) |
117| Props | 5 or fewer (group into object if exceeded) |
118| Custom Hooks | Always extract when reusing logic |
119| Error Boundaries | Set at the page level |
120| Loading States | Provide loading UI for all async ops |
121| Form Validation | Validate on both client and server |
122
123## Performance Patterns
124
125| Pattern | When | Tool |
126|---------|------|------|
127| Memoization | Expensive computation | `useMemo`, `React.memo` |
128| Lazy Loading | Bundle size | `React.lazy`, `next/dynamic` |
129| Virtualization | 1000+ item lists | `@tanstack/react-virtual` |
130| Image Optimization | Image loading | `next/image` |
131| Optimistic Updates | Immediate feedback | React Query `onMutate` |
132| Debounce | Search, input | `useDeferredValue` or custom hook |
133
134## Error Handling
135
136### Hierarchical Error Boundaries
137```
138RootErrorBoundary (global)
139 └── LayoutErrorBoundary (per section)
140 └── ComponentErrorFallback (individual)
141```
142
143### API Error Handling
144| HTTP Status | Client Handling |
145|------------|----------------|
146| 401 | Auto logout + redirect |
147| 403 | Unauthorized UI |
148| 404 | Not Found page |
149| 422 | Per-field form error |
150| 429 | Retry + wait notice |
151| 500 | Generic error + retry button |
152
153## Accessibility Checklist
154
155- [ ] Alt text on all images
156- [ ] Keyboard navigation (Tab, Enter, Escape)
157- [ ] ARIA labels (aria-label, role)
158- [ ] Color contrast 4.5:1 or above
159- [ ] Visible focus indicator
160- [ ] Semantic HTML (button, nav, main, section)
161
162<!-- moai:evolvable-start id="rationalizations" -->
163## Common Rationalizations
164
165| Rationalization | Reality |
166|---|---|
167| "useEffect is fine for data fetching in React 19" | React 19 provides use() and server components for data fetching. useEffect for fetch is a legacy pattern that causes waterfalls. |
168| "Global state is simpler than prop drilling" | Global state couples distant components. Prop drilling or composition via children is more predictable and testable. |
169| "I will add TypeScript types later" | Untyped components accumulate any-typed callers. Retrofitting types into a used component is much harder than starting typed. |
170| "This component does not need memoization" | Premature memoization is waste, but components rendering lists or expensive trees should be profiled, not assumed fast. |
171| "CSS-in-JS is fine, everyone uses it" | CSS-in-JS adds runtime overhead and bundle size. Tailwind or CSS Modules achieve the same scoping without the cost. |
172
173<!-- moai:evolvable-end -->
174
175<!-- moai:evolvable-start id="red-flags" -->
176## Red Flags
177
178- useEffect used for data fetching when server components or use() are available
179- Component receives more than 5 props without decomposition or object grouping
180- State management library used for server-cacheable data (use React Query or SWR instead)
181- Inline styles or hardcoded pixel values instead of design tokens
182- Component missing error boundary wrapping for async operations
183
184<!-- moai:evolvable-end -->
185
186<!-- moai:evolvable-start id="verification" -->
187## Verification
188
189- [ ] Data fetching uses server components, use(), or React Query (not useEffect + fetch)
190- [ ] Components have TypeScript interfaces for all props
191- [ ] Error boundaries wrap components with async operations
192- [ ] Accessibility checklist completed (alt text, keyboard nav, ARIA, contrast, focus, semantics)
193- [ ] No inline styles or hardcoded color/spacing values (design tokens used)
194- [ ] Component renders correctly in React Strict Mode (no double-effect issues)
195
196<!-- moai:evolvable-end -->