{"id":"e54dc8be-b6cb-45bc-b98a-053f31f9f52e","entityType":"agent","slug":"clawhub-skills-1kalin-afrexai-react-production","name":"afrexai-react-production","canonicalUrl":"https://www.xpersona.co/agent/clawhub-skills-1kalin-afrexai-react-production","canonicalPath":"/agent/clawhub-skills-1kalin-afrexai-react-production","generatedAt":"2026-10-10T07:18:04.355Z","source":"CLAWHUB","claimStatus":"UNCLAIMED","verificationTier":"NONE","summary":{"evidence":{"source":"editorial-content","verified":true,"confidence":"high","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":null},"description":"Complete methodology for building production-grade React applications with architecture decisions, component design, state management, performance optimization, testing, and deployment. --- name: afrexai-react-production description: Complete methodology for building production-grade React applications with architecture decisions, component design, state management, performance optimization, testing, and deployment. --- React Production Engineering Complete methodology for building production-grade React applications. Covers architecture decisions, component design, state management, performance opt","descriptionLabel":"Technical summary","evidenceSummary":"Capability contract not published. No trust telemetry is available yet. Last updated 4/15/2026.","installCommand":"clawhub skill install skills:1kalin:afrexai-react-production","sourceUrl":"https://github.com/openclaw/skills/tree/main/skills/1kalin/afrexai-react-production","homepage":null,"primaryLinks":[{"label":"View on ClawHub","url":"https://github.com/openclaw/skills/tree/main/skills/1kalin/afrexai-react-production","kind":"source"}],"safetyScore":84,"overallRank":62,"popularityScore":50,"trustScore":null,"claimedByName":null,"isOwner":false,"seoDescription":"Complete methodology for building production-grade React applications with architecture decisions, component design, state management, performance optimization,"},"coverage":{"evidence":{"source":"public-profile","verified":false,"confidence":"medium","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":null},"protocols":[{"protocol":"OPENCLEW","label":"OpenClaw","status":"self-declared","notes":"Declared in the public agent profile."}],"capabilities":[],"verifiedCount":0,"selfDeclaredCount":1,"capabilityMatrix":{"rows":[{"key":"OPENCLEW","type":"protocol","support":"unknown","confidenceSource":"profile","notes":"Listed on profile"}],"flattenedTokens":"protocol:OPENCLEW|unknown|profile"}},"adoption":{"evidence":{"source":"no-adoption-signals","verified":false,"confidence":"low","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":"No source adoption metrics were available."},"stars":null,"forks":null,"downloads":null,"packageName":null,"latestVersion":null,"tractionLabel":null},"release":{"evidence":{"source":"agent-index","verified":false,"confidence":"medium","updatedAt":"2026-02-25T06:17:59.830Z","emptyReason":null},"lastUpdatedAt":"2026-04-15T00:45:39.800Z","lastCrawledAt":"2026-02-25T06:17:59.830Z","lastIndexedAt":null,"nextCrawlAt":"2026-02-26T06:17:59.830Z","lastVerifiedAt":null,"highlights":[]},"execution":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No published capability contract is available yet."},"installCommand":"clawhub skill install skills:1kalin:afrexai-react-production","setupComplexity":"low","setupSteps":["Setup complexity is LOW. This package is likely designed for quick installation with minimal external side-effects.","Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data."],"contract":{"contractStatus":"missing","authModes":[],"requires":[],"forbidden":[],"supportsMcp":false,"supportsA2a":false,"supportsStreaming":false,"inputSchemaRef":null,"outputSchemaRef":null,"dataRegion":null,"contractUpdatedAt":null,"sourceUpdatedAt":null,"freshnessSeconds":null},"invocationGuide":{"preferredApi":{"snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-react-production/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-react-production/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-react-production/trust"},"curlExamples":["curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-react-production/snapshot\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-react-production/contract\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-react-production/trust\""],"jsonRequestTemplate":{"query":"summarize this repo","constraints":{"maxLatencyMs":2000,"protocolPreference":["OPENCLEW"]}},"jsonResponseTemplate":{"ok":true,"result":{"summary":"...","confidence":0.9},"meta":{"source":"CLAWHUB","generatedAt":"2026-10-10T07:18:04.354Z"}},"retryPolicy":{"maxAttempts":3,"backoffMs":[500,1500,3500],"retryableConditions":["HTTP_429","HTTP_503","NETWORK_TIMEOUT"]}},"endpoints":{"dossierUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-react-production/dossier","snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-react-production/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-react-production/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-react-production/trust"}},"reliability":{"evidence":{"source":"runtime-metrics","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No trust, reliability, or runtime telemetry is available."},"trust":{"status":"unavailable","handshakeStatus":"UNKNOWN","verificationFreshnessHours":null,"reputationScore":null,"p95LatencyMs":null,"successRate30d":null,"fallbackRate":null,"attempts30d":null,"trustUpdatedAt":null,"trustConfidence":"unknown","sourceUpdatedAt":null,"freshnessSeconds":null},"decisionGuardrails":{"doNotUseIf":["Contract metadata is missing or unavailable for deterministic execution."],"safeUseWhen":[],"riskFlags":["missing_or_unavailable_contract","trust_data_unavailable","schema_references_missing"],"operationalConfidence":"low"},"executionMetrics":{"observedLatencyMsP50":null,"observedLatencyMsP95":null,"estimatedCostUsd":null,"uptime30d":null,"rateLimitRpm":null,"rateLimitBurst":null,"lastVerifiedAt":null,"verificationSource":null},"runtimeMetrics":{"successRate":null,"avgLatencyMs":null,"avgCostUsd":null,"hallucinationRate":null,"retryRate":null,"disputeRate":null,"p50Latency":null,"p95Latency":null,"lastUpdated":null}},"benchmarks":{"evidence":{"source":"no-benchmark-data","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No benchmark suites or observed failure patterns are available."},"suites":[],"failurePatterns":[]},"artifacts":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"high","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":null},"readme":"---\nname: afrexai-react-production\ndescription: Complete methodology for building production-grade React applications with architecture decisions, component design, state management, performance optimization, testing, and deployment.\n---\n\n# React Production Engineering\n\nComplete methodology for building production-grade React applications. Covers architecture decisions, component design, state management, performance optimization, testing, and deployment — not just API reference, but engineering methodology with decision frameworks, templates, and scoring systems.\n\n## Phase 1: Architecture Assessment\n\n### Quick Health Check (score /16)\n- [ ] Component tree depth < 6 levels (+2)\n- [ ] No prop drilling past 2 levels (+2)\n- [ ] Bundle size < 200KB gzipped (+2)\n- [ ] LCP < 2.5s on 4G (+2)\n- [ ] Test coverage > 70% on business logic (+2)\n- [ ] Zero `any` types in production code (+2)\n- [ ] No direct DOM manipulation (+2)\n- [ ] Consistent error boundaries (+2)\n\n### Architecture Brief\n\n```yaml\nproject:\n  name: \"\"\n  type: \"\" # spa | ssr | hybrid | static\n  framework: \"\" # next | remix | vite-spa | astro\n  scale: \"\" # small (<20 routes) | medium (20-100) | large (100+)\n  team_size: \"\" # solo | small (2-5) | medium (6-15) | large (15+)\ncurrent_state:\n  react_version: \"\" # 18 | 19\n  typescript: true\n  router: \"\" # react-router | next-app | tanstack-router\n  state_management: \"\" # useState | zustand | jotai | redux | tanstack-query\n  styling: \"\" # tailwind | css-modules | styled-components | vanilla-extract\n  testing: \"\" # vitest | jest | playwright | cypress\n  ci_cd: \"\" # github-actions | gitlab-ci | vercel\npain_points: []\ngoals: []\n```\n\n### Framework Selection Decision Matrix\n\n| Factor | Vite SPA | Next.js | Remix | Astro |\n|--------|----------|---------|-------|-------|\n| SEO needed | ❌ | ✅ Best | ✅ Good | ✅ Best |\n| Dashboard/app | ✅ Best | ✅ Good | ✅ Good | ❌ |\n| Content-heavy | ❌ | ✅ Good | ✅ Good | ✅ Best |\n| Team familiarity | ✅ Simple | ⚠️ Learning curve | ⚠️ Web standards | ⚠️ Islands |\n| Deployment | Anywhere | Vercel optimal | Anywhere | Anywhere |\n| Bundle size | You control | Framework overhead | Smaller | Minimal JS |\n\n**Decision rules:**\n1. Dashboard/internal tool with no SEO → Vite SPA\n2. Marketing + app hybrid → Next.js\n3. Content-first with some interactivity → Astro\n4. Web-standards-first, nested layouts → Remix\n5. Default for most SaaS products → Next.js\n\n---\n\n## Phase 2: Project Structure & Conventions\n\n### Recommended Feature-Based Structure\n\n```\nsrc/\n├── app/                    # Routes/pages (framework-specific)\n├── features/               # Feature modules (THE core pattern)\n│   ├── auth/\n│   │   ├── components/     # Feature-specific components\n│   │   ├── hooks/          # Feature-specific hooks\n│   │   ├── api/            # API calls & types\n│   │   ├── utils/          # Feature utilities\n│   │   ├── types.ts        # Feature types\n│   │   └── index.ts        # Public API (barrel export)\n│   ├── dashboard/\n│   └── settings/\n├── shared/                 # Cross-feature shared code\n│   ├── components/         # Generic UI components\n│   │   ├── ui/             # Primitives (Button, Input, Card)\n│   │   └── layout/         # Layout components\n│   ├── hooks/              # Generic hooks\n│   ├── lib/                # Utilities, constants\n│   └── types/              # Global types\n├── providers/              # Context providers\n└── styles/                 # Global styles\n```\n\n### 7 Structure Rules\n1. **Feature isolation** — features/ never import from other features directly; use shared/ or events\n2. **Barrel exports** — every feature has index.ts that defines its public API\n3. **Colocation** — tests, stories, and styles live next to their component\n4. **Max file size** — 300 lines. If bigger, split\n5. **Max component size** — 50 lines of JSX. If bigger, extract\n6. **No circular deps** — enforce with eslint-plugin-import\n7. **Types colocated** — feature types in feature, shared types in shared/types\n\n### Naming Conventions\n\n```\nComponents:     PascalCase.tsx       (UserProfile.tsx)\nHooks:          useCamelCase.ts      (useAuth.ts)\nUtilities:      camelCase.ts         (formatCurrency.ts)\nTypes:          PascalCase.ts        (User.ts) or types.ts\nConstants:      SCREAMING_SNAKE.ts   (API_ENDPOINTS.ts)\nTest files:     *.test.tsx           (UserProfile.test.tsx)\nStory files:    *.stories.tsx        (Button.stories.tsx)\n```\n\n---\n\n## Phase 3: Component Design Patterns\n\n### Component Anatomy Template\n\n```tsx\n// 1. Imports (grouped: react → third-party → internal → types → styles)\nimport { useState, useCallback, memo } from 'react'\nimport { clsx } from 'clsx'\nimport { Button } from '@/shared/components/ui'\nimport type { User } from '../types'\n\n// 2. Types (exported for reuse)\nexport interface UserCardProps {\n  user: User\n  onEdit?: (id: string) => void\n  variant?: 'compact' | 'full'\n  className?: string\n}\n\n// 3. Component (named export, not default)\nexport const UserCard = memo(function UserCard({\n  user,\n  onEdit,\n  variant = 'full',\n  className,\n}: UserCardProps) {\n  // 4. Hooks first\n  const [isExpanded, setIsExpanded] = useState(false)\n\n  // 5. Derived state (no useEffect for derived!)\n  const displayName = `${user.firstName} ${user.lastName}`\n\n  // 6. Handlers (useCallback for passed-down refs)\n  const handleEdit = useCallback(() => {\n    onEdit?.(user.id)\n  }, [onEdit, user.id])\n\n  // 7. Early returns for edge cases\n  if (!user) return null\n\n  // 8. JSX (max 50 lines)\n  return (\n    <div className={clsx('rounded-lg border p-4', className)}>\n      <h3>{displayName}</h3>\n      {variant === 'full' && <p>{user.bio}</p>}\n      {onEdit && <Button onClick={handleEdit}>Edit</Button>}\n    </div>\n  )\n})\n```\n\n### Component Composition Patterns\n\n**1. Compound Components (for related UI groups)**\n```tsx\n// Usage: <Tabs><Tabs.List><Tabs.Tab>A</Tabs.Tab></Tabs.List><Tabs.Panel>...</Tabs.Panel></Tabs>\nconst TabsContext = createContext<TabsContextType | null>(null)\n\nexport function Tabs({ children, defaultValue }: TabsProps) {\n  const [activeTab, setActiveTab] = useState(defaultValue)\n  return (\n    <TabsContext.Provider value={{ activeTab, setActiveTab }}>\n      {children}\n    </TabsContext.Provider>\n  )\n}\nTabs.List = TabsList\nTabs.Tab = TabsTab\nTabs.Panel = TabsPanel\n```\n\n**2. Render Props (for flexible rendering logic)**\n```tsx\nexport function DataList<T>({ items, renderItem, renderEmpty }: DataListProps<T>) {\n  if (items.length === 0) return renderEmpty?.() ?? <EmptyState />\n  return <ul>{items.map((item, i) => <li key={i}>{renderItem(item)}</li>)}</ul>\n}\n```\n\n**3. Higher-Order Components (for cross-cutting concerns — use sparingly)**\n```tsx\nexport function withAuth<P>(Component: ComponentType<P>) {\n  return function AuthenticatedComponent(props: P) {\n    const { user, isLoading } = useAuth()\n    if (isLoading) return <Spinner />\n    if (!user) return <Navigate to=\"/login\" />\n    return <Component {...props} />\n  }\n}\n```\n\n### 10 Component Rules\n1. **One component per file** — always\n2. **Named exports** — never default exports (refactoring safety)\n3. **Props interface** — always explicit, always exported\n4. **No business logic in components** — extract to hooks\n5. **No inline styles** — use Tailwind classes or CSS modules\n6. **No string refs** — useRef only\n7. **No index as key** — use stable identifiers\n8. **Memo strategically** — not everywhere, only for expensive renders\n9. **Children over props** — prefer composition over configuration\n10. **Accessible by default** — semantic HTML, ARIA when needed\n\n---\n\n## Phase 4: State Management Decision Framework\n\n### State Type Decision Tree\n\n```\nIs it server data (from API)?\n├─ YES → TanStack Query (or SWR) — NEVER Redux/Zustand for server state\n│\n└─ NO → Is it shared across features?\n    ├─ YES → Is it complex with many actions?\n    │   ├─ YES → Zustand (or Redux Toolkit if team knows it)\n    │   └─ NO → Jotai (atomic) or Zustand (simple store)\n    │\n    └─ NO → Is it shared within a feature?\n        ├─ YES → Context + useReducer (or Zustand feature store)\n        └─ NO → useState / useReducer (component-local)\n```\n\n### State Management Comparison\n\n| Tool | Best For | Bundle | Learning | Team Size |\n|------|----------|--------|----------|-----------|\n| useState | Component-local | 0 KB | None | Any |\n| useReducer | Complex local state | 0 KB | Low | Any |\n| Context | Feature-scoped, low-frequency | 0 KB | Low | Any |\n| Zustand | Global client state | 1.1 KB | Low | Any |\n| Jotai | Atomic derived state | 3.4 KB | Medium | Small-Med |\n| TanStack Query | Server state | 12 KB | Medium | Any |\n| Redux Toolkit | Complex global + middleware | 11 KB | High | Large |\n\n### Server State with TanStack Query\n\n```tsx\n// api/users.ts — query key factory pattern\nexport const userKeys = {\n  all: ['users'] as const,\n  lists: () => [...userKeys.all, 'list'] as const,\n  list: (filters: Filters) => [...userKeys.lists(), filters] as const,\n  details: () => [...userKeys.all, 'detail'] as const,\n  detail: (id: string) => [...userKeys.details(), id] as const,\n}\n\n// hooks/useUsers.ts\nexport function useUsers(filters: Filters) {\n  return useQuery({\n    queryKey: userKeys.list(filters),\n    queryFn: () => fetchUsers(filters),\n    staleTime: 5 * 60 * 1000, // 5 min\n    placeholderData: keepPreviousData,\n  })\n}\n\nexport function useUpdateUser() {\n  const queryClient = useQueryClient()\n  return useMutation({\n    mutationFn: updateUser,\n    onMutate: async (newUser) => {\n      // Optimistic update\n      await queryClient.cancelQueries({ queryKey: userKeys.detail(newUser.id) })\n      const previous = queryClient.getQueryData(userKeys.detail(newUser.id))\n      queryClient.setQueryData(userKeys.detail(newUser.id), newUser)\n      return { previous }\n    },\n    onError: (err, newUser, context) => {\n      queryClient.setQueryData(userKeys.detail(newUser.id), context?.previous)\n    },\n    onSettled: (data, err, variables) => {\n      queryClient.invalidateQueries({ queryKey: userKeys.detail(variables.id) })\n      queryClient.invalidateQueries({ queryKey: userKeys.lists() })\n    },\n  })\n}\n```\n\n### Client State with Zustand\n\n```tsx\n// stores/useUIStore.ts — thin, focused stores\ninterface UIStore {\n  sidebarOpen: boolean\n  theme: 'light' | 'dark' | 'system'\n  toggleSidebar: () => void\n  setTheme: (theme: UIStore['theme']) => void\n}\n\nexport const useUIStore = create<UIStore>()(\n  persist(\n    (set) => ({\n      sidebarOpen: true,\n      theme: 'system',\n      toggleSidebar: () => set((s) => ({ sidebarOpen: !s.sidebarOpen })),\n      setTheme: (theme) => set({ theme }),\n    }),\n    { name: 'ui-preferences' }\n  )\n)\n\n// Usage: const theme = useUIStore((s) => s.theme) — always use selectors!\n```\n\n### 5 State Management Rules\n1. **Server state ≠ client state** — never mix them in the same store\n2. **Smallest scope possible** — useState > Context > Zustand > Redux\n3. **No useEffect for derived state** — use useMemo or compute inline\n4. **Selectors always** — `useStore(s => s.field)` not `useStore()`\n5. **URL is state** — search params, filters, pagination → URL, not React state\n\n---\n\n## Phase 5: Hooks Engineering\n\n### Custom Hook Template\n\n```tsx\n// hooks/useDebounce.ts\nexport function useDebounce<T>(value: T, delayMs: number = 300): T {\n  const [debouncedValue, setDebouncedValue] = useState(value)\n\n  useEffect(() => {\n    const timer = setTimeout(() => setDebouncedValue(value), delayMs)\n    return () => clearTimeout(timer)\n  }, [value, delayMs])\n\n  return debouncedValue\n}\n```\n\n### Essential Custom Hooks Library\n\n| Hook | Purpose | When to Use |\n|------|---------|-------------|\n| `useDebounce` | Debounce value changes | Search inputs, resize |\n| `useMediaQuery` | Responsive breakpoints | Conditional rendering |\n| `useLocalStorage` | Persistent local state | Preferences, drafts |\n| `useIntersection` | Viewport detection | Lazy load, infinite scroll |\n| `usePrevious` | Track previous value | Animations, comparisons |\n| `useClickOutside` | Detect outside clicks | Dropdowns, modals |\n| `useEventListener` | Safe event binding | Keyboard, scroll, resize |\n| `useToggle` | Boolean state toggle | Modals, accordions |\n\n### Hook Rules (beyond React's rules)\n1. **One concern per hook** — `useUserSearch` not `useEverything`\n2. **Return tuple or object** — tuple for 1-2 values, object for 3+\n3. **Accept options object** — `useDebounce(value, { delay: 300 })` scales better\n4. **Handle cleanup** — every subscription/timer needs cleanup in useEffect return\n5. **No hooks in conditions** — extract conditional logic into the hook body\n6. **Test hooks independently** — use `renderHook` from testing-library\n\n---\n\n## Phase 6: TypeScript Integration\n\n### Strict Configuration\n\n```json\n{\n  \"compilerOptions\": {\n    \"strict\": true,\n    \"noUncheckedIndexedAccess\": true,\n    \"noImplicitOverride\": true,\n    \"exactOptionalPropertyTypes\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"paths\": {\n      \"@/*\": [\"./src/*\"]\n    }\n  }\n}\n```\n\n### Essential Type Patterns\n\n```tsx\n// 1. Discriminated unions for state machines\ntype AsyncState<T> =\n  | { status: 'idle' }\n  | { status: 'loading' }\n  | { status: 'success'; data: T }\n  | { status: 'error'; error: Error }\n\n// 2. Polymorphic components\ntype ButtonProps<C extends ElementType = 'button'> = {\n  as?: C\n  variant?: 'primary' | 'secondary'\n} & ComponentPropsWithoutRef<C>\n\nexport function Button<C extends ElementType = 'button'>({\n  as,\n  variant = 'primary',\n  ...props\n}: ButtonProps<C>) {\n  const Component = as || 'button'\n  return <Component {...props} />\n}\n\n// 3. Branded types for IDs\ntype UserId = string & { __brand: 'UserId' }\ntype PostId = string & { __brand: 'PostId' }\n\n// 4. Zod for runtime validation\nconst userSchema = z.object({\n  id: z.string().uuid(),\n  email: z.string().email(),\n  role: z.enum(['admin', 'user', 'viewer']),\n})\ntype User = z.infer<typeof userSchema>\n```\n\n### 5 TypeScript Rules\n1. **Zero `any`** — use `unknown` and narrow, or generics\n2. **Zod at boundaries** — validate all external data (API, forms, URL params)\n3. **Discriminated unions over optional fields** — `{ status: 'success'; data: T }` not `{ data?: T; error?: Error }`\n4. **Branded types for IDs** — prevent `userId` being passed where `postId` expected\n5. **Satisfies over as** — `config satisfies Config` preserves inference; `as Config` lies\n\n---\n\n## Phase 7: Performance Optimization\n\n### Performance Budget\n\n| Metric | Target | Measurement |\n|--------|--------|-------------|\n| First Contentful Paint | < 1.8s | Lighthouse |\n| Largest Contentful Paint | < 2.5s | Lighthouse |\n| Interaction to Next Paint | < 200ms | Lighthouse |\n| Cumulative Layout Shift | < 0.1 | Lighthouse |\n| Bundle size (gzipped) | < 200 KB | webpack-bundle-analyzer |\n| JS execution (main thread) | < 3s | Chrome DevTools |\n\n### Optimization Priority Stack\n\n| Priority | Technique | Impact | Effort |\n|----------|-----------|--------|--------|\n| P0 | Code splitting (route-based) | 🔴 High | Low |\n| P0 | Image optimization (next/image, srcset) | 🔴 High | Low |\n| P1 | Tree shaking (named imports) | 🟡 Medium | Low |\n| P1 | Virtualization for long lists | 🟡 Medium | Medium |\n| P1 | Debounce expensive operations | 🟡 Medium | Low |\n| P2 | React.memo on expensive components | 🟢 Low-Med | Low |\n| P2 | useMemo/useCallback for expensive calculations | 🟢 Low-Med | Low |\n| P3 | Web Workers for heavy computation | 🟢 Low | High |\n\n### Code Splitting Patterns\n\n```tsx\n// 1. Route-based (automatic with Next.js, manual with React Router)\nconst Dashboard = lazy(() => import('./features/dashboard'))\nconst Settings = lazy(() => import('./features/settings'))\n\n// 2. Component-based (heavy components)\nconst Chart = lazy(() => import('./components/Chart'))\nconst MarkdownEditor = lazy(() =>\n  import('./components/MarkdownEditor').then(m => ({ default: m.MarkdownEditor }))\n)\n\n// 3. Library-based (heavy third-party)\nconst { PDFViewer } = await import('@react-pdf/renderer')\n```\n\n### React Compiler (React 19+)\n```tsx\n// With React Compiler enabled, manual memo/useMemo/useCallback become unnecessary\n// The compiler auto-memoizes. Remove manual optimizations:\n// ❌ const memoized = useMemo(() => expensiveCalc(data), [data])\n// ✅ const memoized = expensiveCalc(data)  // compiler handles it\n\n// Enable in babel config:\n// plugins: [['babel-plugin-react-compiler', {}]]\n```\n\n### Rendering Performance Rules\n1. **Never create components inside components** — define at module level\n2. **Never create objects/arrays in JSX** — `style={{ color: 'red' }}` rerenders always\n3. **Children as props prevent rerender** — `<Layout><ExpensiveChild /></Layout>`\n4. **Key must be stable and unique** — not index, not `Math.random()`\n5. **Avoid context value churn** — memoize provider value or split contexts\n6. **Profile before optimizing** — React DevTools Profiler, not guesswork\n\n---\n\n## Phase 8: Error Handling & Resilience\n\n### Error Boundary Architecture\n\n```tsx\n// Three levels of error boundaries:\n// 1. App-level (catches everything, shows full-page error)\n// 2. Feature-level (isolates feature failures)\n// 3. Component-level (for risky widgets — charts, third-party)\n\n// Modern error boundary with react-error-boundary\nimport { ErrorBoundary, FallbackProps } from 'react-error-boundary'\n\nfunction FeatureErrorFallback({ error, resetErrorBoundary }: FallbackProps) {\n  return (\n    <div role=\"alert\" className=\"rounded-lg border-red-200 bg-red-50 p-4\">\n      <h3>Something went wrong</h3>\n      <pre className=\"text-sm text-red-600\">{error.message}</pre>\n      <button onClick={resetErrorBoundary}>Try again</button>\n    </div>\n  )\n}\n\n// Usage:\n<ErrorBoundary FallbackComponent={FeatureErrorFallback} onReset={() => queryClient.clear()}>\n  <DashboardFeature />\n</ErrorBoundary>\n```\n\n### Error Handling Checklist\n- [ ] App-level error boundary wrapping entire app\n- [ ] Feature-level boundaries for each major feature\n- [ ] API errors handled in TanStack Query's `onError` / error states\n- [ ] Form validation errors shown inline (not alerts)\n- [ ] 404 page for unknown routes\n- [ ] Offline detection and graceful degradation\n- [ ] Error reporting to monitoring (Sentry, etc.)\n- [ ] User-friendly error messages (no stack traces in production)\n\n---\n\n## Phase 9: Forms & Validation\n\n### Form Library Decision\n\n| Library | Best For | Bundle | Renders |\n|---------|----------|--------|---------|\n| React Hook Form | Most forms | 9 KB | Minimal (uncontrolled) |\n| Formik | Simple forms | 13 KB | Every keystroke |\n| TanStack Form | Type-safe complex | 5 KB | Controlled |\n| Native | 1-2 field forms | 0 KB | You control |\n\n**Default recommendation: React Hook Form + Zod**\n\n### Form Pattern\n\n```tsx\nconst schema = z.object({\n  email: z.string().email('Invalid email'),\n  password: z.string().min(8, 'Min 8 characters'),\n  role: z.enum(['admin', 'user']),\n})\ntype FormData = z.infer<typeof schema>\n\nexport function LoginForm({ onSubmit }: { onSubmit: (data: FormData) => void }) {\n  const form = useForm<FormData>({\n    resolver: zodResolver(schema),\n    defaultValues: { email: '', password: '', role: 'user' },\n  })\n\n  return (\n    <form onSubmit={form.handleSubmit(onSubmit)} noValidate>\n      <label htmlFor=\"email\">Email</label>\n      <input id=\"email\" type=\"email\" {...form.register('email')} aria-invalid={!!form.formState.errors.email} />\n      {form.formState.errors.email && (\n        <p role=\"alert\">{form.formState.errors.email.message}</p>\n      )}\n      {/* ... more fields */}\n      <button type=\"submit\" disabled={form.formState.isSubmitting}>\n        {form.formState.isSubmitting ? 'Signing in...' : 'Sign in'}\n      </button>\n    </form>\n  )\n}\n```\n\n---\n\n## Phase 10: Testing Strategy\n\n### Test Pyramid for React\n\n| Level | Tool | Coverage Target | What to Test |\n|-------|------|-----------------|-------------|\n| Unit | Vitest | 80% business logic | Hooks, utilities, reducers |\n| Component | Testing Library | Key user flows | Rendering, interactions, a11y |\n| Integration | Testing Library | Feature flows | Multi-component workflows |\n| E2E | Playwright | Critical paths | Auth, checkout, core flows |\n| Visual | Chromatic/Percy | UI components | Regression detection |\n\n### Testing Patterns\n\n```tsx\n// Component test (Testing Library philosophy: test behavior, not implementation)\nimport { render, screen } from '@testing-library/react'\nimport userEvent from '@testing-library/user-event'\n\ndescribe('UserCard', () => {\n  it('calls onEdit when edit button clicked', async () => {\n    const user = userEvent.setup()\n    const onEdit = vi.fn()\n    render(<UserCard user={mockUser} onEdit={onEdit} />)\n\n    await user.click(screen.getByRole('button', { name: /edit/i }))\n    expect(onEdit).toHaveBeenCalledWith(mockUser.id)\n  })\n\n  it('does not render edit button when onEdit not provided', () => {\n    render(<UserCard user={mockUser} />)\n    expect(screen.queryByRole('button', { name: /edit/i })).not.toBeInTheDocument()\n  })\n})\n```\n\n### 7 Testing Rules\n1. **Test behavior, not implementation** — never test state directly or useEffect\n2. **Use accessible queries** — `getByRole` > `getByTestId` > `getByText`\n3. **User events over fireEvent** — `userEvent.click` simulates real interaction\n4. **One assertion per concept** — not one per test, but focused assertions\n5. **Mock at boundaries** — API calls, not internal functions\n6. **No snapshot tests** — they break on every change and test nothing meaningful\n7. **Arrange-Act-Assert** — clear structure in every test\n\n---\n\n## Phase 11: Accessibility (a11y)\n\n### 10-Point Accessibility Checklist\n1. **Semantic HTML** — `<button>` not `<div onClick>`, `<nav>` not `<div class=\"nav\">`\n2. **Keyboard navigation** — every interactive element reachable via Tab, operable via Enter/Space\n3. **Focus management** — visible focus indicator, logical tab order, focus trap in modals\n4. **Alt text** — every `<img>` has descriptive alt (or `alt=\"\"` if decorative)\n5. **Color contrast** — 4.5:1 for normal text, 3:1 for large text (WCAG AA)\n6. **ARIA labels** — `aria-label` for icon-only buttons, `aria-describedby` for hints\n7. **Live regions** — `aria-live=\"polite\"` for dynamic content (toasts, form errors)\n8. **Reduced motion** — respect `prefers-reduced-motion` for animations\n9. **Screen reader testing** — test with VoiceOver (Mac) or NVDA (Windows)\n10. **Automated scanning** — axe-core in CI (`vitest-axe` or `@axe-core/playwright`)\n\n---\n\n## Phase 12: Production Deployment Checklist\n\n### Mandatory (P0)\n- [ ] TypeScript strict mode, zero errors\n- [ ] All tests passing\n- [ ] Bundle analyzed, no unexpected large dependencies\n- [ ] Error boundaries at app and feature level\n- [ ] Environment variables validated at build time\n- [ ] Security headers configured (CSP, HSTS, X-Frame-Options)\n- [ ] SEO meta tags (title, description, OG tags)\n- [ ] Analytics/error monitoring integrated\n- [ ] Performance budget met (LCP < 2.5s)\n\n### Recommended (P1)\n- [ ] Storybook for component library\n- [ ] Visual regression tests\n- [ ] a11y automated checks in CI\n- [ ] Feature flags for risky features\n- [ ] Preview deployments for PRs\n- [ ] Bundle size CI check (fail if +10%)\n\n### Recommended Stack (2025+)\n\n| Layer | Recommendation | Alternative |\n|-------|---------------|-------------|\n| Framework | Next.js 15 | Remix, Vite SPA |\n| Language | TypeScript (strict) | — |\n| Styling | Tailwind CSS v4 | CSS Modules |\n| Components | shadcn/ui | Radix, Headless UI |\n| State (server) | TanStack Query v5 | SWR |\n| State (client) | Zustand | Jotai |\n| Forms | React Hook Form + Zod | TanStack Form |\n| Testing | Vitest + Testing Library | Jest |\n| E2E | Playwright | Cypress |\n| Linting | Biome | ESLint + Prettier |\n| Auth | Auth.js (NextAuth) | Clerk, Lucia |\n| Database | Drizzle ORM | Prisma |\n| Deployment | Vercel | Cloudflare, Fly.io |\n| Monitoring | Sentry | Datadog |\n\n---\n\n## Quality Scoring (0-100)\n\n| Dimension | Weight | What to Score |\n|-----------|--------|--------------|\n| Architecture | 20% | Structure, separation, patterns |\n| Type safety | 15% | Strict TS, zero any, Zod boundaries |\n| Performance | 15% | Core Web Vitals, bundle size |\n| Testing | 15% | Coverage, quality, pyramid |\n| Accessibility | 10% | WCAG AA, keyboard, screen reader |\n| State management | 10% | Right tool, no prop drilling |\n| Error handling | 10% | Boundaries, user-friendly, monitoring |\n| Developer experience | 5% | Linting, formatting, CI speed |\n\n**Grading:** 90+ World-class | 75-89 Production-ready | 60-74 Needs work | <60 Tech debt crisis\n\n---\n\n## 10 Common Mistakes\n\n| # | Mistake | Fix |\n|---|---------|-----|\n| 1 | useEffect for derived state | Compute inline or useMemo |\n| 2 | Prop drilling 5+ levels deep | Context, Zustand, or composition |\n| 3 | Fetching in useEffect | TanStack Query or framework loaders |\n| 4 | Default exports everywhere | Named exports for refactoring safety |\n| 5 | Testing implementation details | Test behavior with Testing Library |\n| 6 | Giant components (500+ lines) | Extract hooks and sub-components |\n| 7 | No error boundaries | Add at app, feature, and widget level |\n| 8 | Redux for server state | TanStack Query for API data |\n| 9 | Ignoring a11y until the end | Build accessible from day 1 |\n| 10 | No TypeScript strict mode | Enable strict, fix all errors |\n\n---\n\n## Natural Language Commands\n\n- \"Set up a new React project\" → Phase 1-2 architecture + structure\n- \"Review my component\" → Phase 3 rules + quality scoring\n- \"Help me choose state management\" → Phase 4 decision tree\n- \"Optimize performance\" → Phase 7 priority stack + profiling\n- \"Add error handling\" → Phase 8 error boundary architecture\n- \"Build a form\" → Phase 9 React Hook Form + Zod pattern\n- \"Write tests for this component\" → Phase 10 testing patterns\n- \"Check accessibility\" → Phase 11 checklist\n- \"Prepare for production\" → Phase 12 deployment checklist\n- \"Audit my React app\" → Full quality scoring across all phases\n- \"Migrate from class components\" → Modern patterns + hooks\n- \"Upgrade to React 19\" → Compiler, Server Components, Actions\n\n---\n\n## ⚡ Level Up Your React Development\n\nThis skill gives you the methodology. For industry-specific implementation patterns, grab an **AfrexAI Context Pack** ($47):\n\n- **SaaS Context Pack** — SaaS-specific React patterns, billing UI, dashboard architecture\n- **Fintech Context Pack** — Financial UI patterns, real-time data, compliance\n- **Healthcare Context Pack** — HIPAA-compliant UI, patient data handling\n\n👉 **Browse all 10 packs:** https://afrexai-cto.github.io/context-packs/\n\n### 🔗 More Free Skills by AfrexAI\n- `afrexai-nextjs-production` — Next.js production engineering\n- `afrexai-vibe-coding` — AI-assisted development methodology\n- `afrexai-technical-seo` — SEO for React SPAs and SSR\n- `afrexai-test-automation-engineering` — Complete testing strategy\n- `afrexai-ui-design-system` — Design system architecture\n","readmeExcerpt":"--- name: afrexai-react-production description: Complete methodology for building production-grade React applications with architecture decisions, component design, state management, performance optimization, testing, and deployment. --- React Production Engineering Complete methodology for building production-grade React applications. Covers architecture decisions, component design, state management, performance opt","codeSnippets":[],"executableExamples":[{"language":"yaml","snippet":"project:\n  name: \"\"\n  type: \"\" # spa | ssr | hybrid | static\n  framework: \"\" # next | remix | vite-spa | astro\n  scale: \"\" # small (<20 routes) | medium (20-100) | large (100+)\n  team_size: \"\" # solo | small (2-5) | medium (6-15) | large (15+)\ncurrent_state:\n  react_version: \"\" # 18 | 19\n  typescript: true\n  router: \"\" # react-router | next-app | tanstack-router\n  state_management: \"\" # useState | zustand | jotai | redux | tanstack-query\n  styling: \"\" # tailwind | css-modules | styled-components | vanilla-extract\n  testing: \"\" # vitest | jest | playwright | cypress\n  ci_cd: \"\" # github-actions | gitlab-ci | vercel\npain_points: []\ngoals: []"},{"language":"text","snippet":"src/\n├── app/                    # Routes/pages (framework-specific)\n├── features/               # Feature modules (THE core pattern)\n│   ├── auth/\n│   │   ├── components/     # Feature-specific components\n│   │   ├── hooks/          # Feature-specific hooks\n│   │   ├── api/            # API calls & types\n│   │   ├── utils/          # Feature utilities\n│   │   ├── types.ts        # Feature types\n│   │   └── index.ts        # Public API (barrel export)\n│   ├── dashboard/\n│   └── settings/\n├── shared/                 # Cross-feature shared code\n│   ├── components/         # Generic UI components\n│   │   ├── ui/             # Primitives (Button, Input, Card)\n│   │   └── layout/         # Layout components\n│   ├── hooks/              # Generic hooks\n│   ├── lib/                # Utilities, constants\n│   └── types/              # Global types\n├── providers/              # Context providers\n└── styles/                 # Global styles"},{"language":"text","snippet":"Components:     PascalCase.tsx       (UserProfile.tsx)\nHooks:          useCamelCase.ts      (useAuth.ts)\nUtilities:      camelCase.ts         (formatCurrency.ts)\nTypes:          PascalCase.ts        (User.ts) or types.ts\nConstants:      SCREAMING_SNAKE.ts   (API_ENDPOINTS.ts)\nTest files:     *.test.tsx           (UserProfile.test.tsx)\nStory files:    *.stories.tsx        (Button.stories.tsx)"},{"language":"tsx","snippet":"// 1. Imports (grouped: react → third-party → internal → types → styles)\nimport { useState, useCallback, memo } from 'react'\nimport { clsx } from 'clsx'\nimport { Button } from '@/shared/components/ui'\nimport type { User } from '../types'\n\n// 2. Types (exported for reuse)\nexport interface UserCardProps {\n  user: User\n  onEdit?: (id: string) => void\n  variant?: 'compact' | 'full'\n  className?: string\n}\n\n// 3. Component (named export, not default)\nexport const UserCard = memo(function UserCard({\n  user,\n  onEdit,\n  variant = 'full',\n  className,\n}: UserCardProps) {\n  // 4. Hooks first\n  const [isExpanded, setIsExpanded] = useState(false)\n\n  // 5. Derived state (no useEffect for derived!)\n  const displayName = `${user.firstName} ${user.lastName}`\n\n  // 6. Handlers (useCallback for passed-down refs)\n  const handleEdit = useCallback(() => {\n    onEdit?.(user.id)\n  }, [onEdit, user.id])\n\n  // 7. Early returns for edge cases\n  if (!user) return null\n\n  // 8. JSX (max 50 lines)\n  return (\n    <div className={clsx('rounded-lg border p-4', className)}>\n      <h3>{displayName}</h3>\n      {variant === 'full' && <p>{user.bio}</p>}\n      {onEdit && <Button onClick={handleEdit}>Edit</Button>}\n    </div>\n  )\n})"},{"language":"tsx","snippet":"// Usage: <Tabs><Tabs.List><Tabs.Tab>A</Tabs.Tab></Tabs.List><Tabs.Panel>...</Tabs.Panel></Tabs>\nconst TabsContext = createContext<TabsContextType | null>(null)\n\nexport function Tabs({ children, defaultValue }: TabsProps) {\n  const [activeTab, setActiveTab] = useState(defaultValue)\n  return (\n    <TabsContext.Provider value={{ activeTab, setActiveTab }}>\n      {children}\n    </TabsContext.Provider>\n  )\n}\nTabs.List = TabsList\nTabs.Tab = TabsTab\nTabs.Panel = TabsPanel"},{"language":"tsx","snippet":"export function DataList<T>({ items, renderItem, renderEmpty }: DataListProps<T>) {\n  if (items.length === 0) return renderEmpty?.() ?? <EmptyState />\n  return <ul>{items.map((item, i) => <li key={i}>{renderItem(item)}</li>)}</ul>\n}"}],"parameters":{},"dependencies":[],"permissions":[],"extractedFiles":[],"languages":["typescript"],"docsSourceLabel":"CLAWHUB","editorialOverview":"Complete methodology for building production-grade React applications with architecture decisions, component design, state management, performance optimization, testing, and deployment. --- name: afrexai-react-production description: Complete methodology for building production-grade React applications with architecture decisions, component design, state management, performance optimization, testing, and deployment. --- React Production Engineering Complete methodology for building production-grade React applications. Covers architecture decisions, component design, state management, performance opt","editorialQuality":{"score":100,"threshold":65,"status":"ready","wordCount":380,"uniquenessScore":61,"reasons":[]}},"media":{"evidence":{"source":"no-media","verified":false,"confidence":"low","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":"No screenshots, media assets, or demo links are available."},"primaryImageUrl":null,"mediaAssetCount":0,"assets":[],"demoUrl":null},"ownerResources":{"evidence":{"source":"unclaimed","verified":false,"confidence":"low","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":"This page has not been claimed by the agent owner."},"hasCustomPage":false,"customPageUpdatedAt":null,"customLinks":[],"structuredLinks":{"docsUrl":null,"demoUrl":null,"supportUrl":null,"pricingUrl":null,"statusUrl":null},"customPage":null},"relatedAgents":{"evidence":{"source":"protocol-neighbors","verified":false,"confidence":"medium","updatedAt":"2026-10-10T07:18:04.355Z","emptyReason":null},"items":[{"id":"8ebccd8e-3863-4187-8355-c3f14e1f9edf","entityType":"agent","canonicalPath":"/agent/iofficeai-aionui","slug":"iofficeai-aionui","name":"AionUi","description":"Free, local, open-source 24/7 Cowork app and OpenClaw for Gemini CLI, Claude Code, Codex, OpenCode, Qwen Code, Goose CLI, Auggie, and more | 🌟 Star if you like it!","url":"https://github.com/iOfficeAI/AionUi","homepage":"https://www.aionui.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-10-09T19:11:12.944Z","createdAt":"2026-02-25T03:38:16.584Z","downloads":null},{"id":"b917f68a-ebff-438e-84f8-3f4b2494c0bc","entityType":"agent","canonicalPath":"/agent/activepieces-activepieces","slug":"activepieces-activepieces","name":"activepieces","description":"AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents","url":"https://github.com/activepieces/activepieces","homepage":"https://www.activepieces.com","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-15T02:22:12.426Z","createdAt":"2026-02-25T03:38:12.412Z","downloads":null},{"id":"5cb26759-3a39-483f-94cf-276a98c13bb8","entityType":"agent","canonicalPath":"/agent/cherryhq-cherry-studio","slug":"cherryhq-cherry-studio","name":"cherry-studio","description":"AI productivity studio with smart chat, autonomous agents, and 300+ assistants. Unified access to frontier LLMs","url":"https://github.com/CherryHQ/cherry-studio","homepage":"https://cherry-ai.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-11T14:38:40.986Z","createdAt":"2026-02-25T03:38:19.379Z","downloads":null},{"id":"6f6582d0-5d76-4f0f-b81d-86520247950b","entityType":"agent","canonicalPath":"/agent/copilotkit-copilotkit","slug":"copilotkit-copilotkit","name":"CopilotKit","description":"The Frontend for Agents & Generative UI. React + Angular","url":"https://github.com/CopilotKit/CopilotKit","homepage":"https://docs.copilotkit.ai","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-03-25T09:50:57.846Z","createdAt":"2026-02-25T03:39:14.617Z","downloads":null}],"links":{"hub":"/agent","source":"/agent/source/clawhub","protocols":[{"label":"OpenClaw","href":"/agent/protocol/openclew"}]}}}