Requirements
- Target platform
- OpenClaw
- Install method
- Manual import
- Extraction
- Extract archive
- Prerequisites
- OpenClaw
- Primary doc
- SKILL.md
Complete methodology for building production-grade React applications with architecture decisions, component design, state management, performance optimizati...
Complete methodology for building production-grade React applications with architecture decisions, component design, state management, performance optimizati...
Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.
I downloaded a skill package from Yavira. Read SKILL.md from the extracted folder and install it by following the included instructions. Then review README.md for any prerequisites, environment setup, or post-install checks. Tell me what you changed and call out any manual steps you could not complete.
I downloaded an updated skill package from Yavira. Read SKILL.md from the extracted folder, compare it with my current installation, and upgrade it while preserving any custom configuration unless the package docs explicitly say otherwise. Then review README.md for any prerequisites, environment setup, or post-install checks. Summarize what changed and any follow-up checks I should run.
Complete 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.
Component tree depth < 6 levels (+2) No prop drilling past 2 levels (+2) Bundle size < 200KB gzipped (+2) LCP < 2.5s on 4G (+2) Test coverage > 70% on business logic (+2) Zero any types in production code (+2) No direct DOM manipulation (+2) Consistent error boundaries (+2)
project: name: "" type: "" # spa | ssr | hybrid | static framework: "" # next | remix | vite-spa | astro scale: "" # small (<20 routes) | medium (20-100) | large (100+) team_size: "" # solo | small (2-5) | medium (6-15) | large (15+) current_state: react_version: "" # 18 | 19 typescript: true router: "" # react-router | next-app | tanstack-router state_management: "" # useState | zustand | jotai | redux | tanstack-query styling: "" # tailwind | css-modules | styled-components | vanilla-extract testing: "" # vitest | jest | playwright | cypress ci_cd: "" # github-actions | gitlab-ci | vercel pain_points: [] goals: []
FactorVite SPANext.jsRemixAstroSEO neededββ Bestβ Goodβ BestDashboard/appβ Bestβ Goodβ GoodβContent-heavyββ Goodβ Goodβ BestTeam familiarityβ Simpleβ οΈ Learning curveβ οΈ Web standardsβ οΈ IslandsDeploymentAnywhereVercel optimalAnywhereAnywhereBundle sizeYou controlFramework overheadSmallerMinimal JS Decision rules: Dashboard/internal tool with no SEO β Vite SPA Marketing + app hybrid β Next.js Content-first with some interactivity β Astro Web-standards-first, nested layouts β Remix Default for most SaaS products β Next.js
src/ βββ app/ # Routes/pages (framework-specific) βββ features/ # Feature modules (THE core pattern) β βββ auth/ β β βββ components/ # Feature-specific components β β βββ hooks/ # Feature-specific hooks β β βββ api/ # API calls & types β β βββ utils/ # Feature utilities β β βββ types.ts # Feature types β β βββ index.ts # Public API (barrel export) β βββ dashboard/ β βββ settings/ βββ shared/ # Cross-feature shared code β βββ components/ # Generic UI components β β βββ ui/ # Primitives (Button, Input, Card) β β βββ layout/ # Layout components β βββ hooks/ # Generic hooks β βββ lib/ # Utilities, constants β βββ types/ # Global types βββ providers/ # Context providers βββ styles/ # Global styles
Feature isolation β features/ never import from other features directly; use shared/ or events Barrel exports β every feature has index.ts that defines its public API Colocation β tests, stories, and styles live next to their component Max file size β 300 lines. If bigger, split Max component size β 50 lines of JSX. If bigger, extract No circular deps β enforce with eslint-plugin-import Types colocated β feature types in feature, shared types in shared/types
Components: PascalCase.tsx (UserProfile.tsx) Hooks: useCamelCase.ts (useAuth.ts) Utilities: camelCase.ts (formatCurrency.ts) Types: PascalCase.ts (User.ts) or types.ts Constants: SCREAMING_SNAKE.ts (API_ENDPOINTS.ts) Test files: *.test.tsx (UserProfile.test.tsx) Story files: *.stories.tsx (Button.stories.tsx)
// 1. Imports (grouped: react β third-party β internal β types β styles) import { useState, useCallback, memo } from 'react' import { clsx } from 'clsx' import { Button } from '@/shared/components/ui' import type { User } from '../types' // 2. Types (exported for reuse) export interface UserCardProps { user: User onEdit?: (id: string) => void variant?: 'compact' | 'full' className?: string } // 3. Component (named export, not default) export const UserCard = memo(function UserCard({ user, onEdit, variant = 'full', className, }: UserCardProps) { // 4. Hooks first const [isExpanded, setIsExpanded] = useState(false) // 5. Derived state (no useEffect for derived!) const displayName = `${user.firstName} ${user.lastName}` // 6. Handlers (useCallback for passed-down refs) const handleEdit = useCallback(() => { onEdit?.(user.id) }, [onEdit, user.id]) // 7. Early returns for edge cases if (!user) return null // 8. JSX (max 50 lines) return ( <div className={clsx('rounded-lg border p-4', className)}> <h3>{displayName}</h3> {variant === 'full' && <p>{user.bio}</p>} {onEdit && <Button onClick={handleEdit}>Edit</Button>} </div> ) })
1. Compound Components (for related UI groups) // Usage: <Tabs><Tabs.List><Tabs.Tab>A</Tabs.Tab></Tabs.List><Tabs.Panel>...</Tabs.Panel></Tabs> const TabsContext = createContext<TabsContextType | null>(null) export function Tabs({ children, defaultValue }: TabsProps) { const [activeTab, setActiveTab] = useState(defaultValue) return ( <TabsContext.Provider value={{ activeTab, setActiveTab }}> {children} </TabsContext.Provider> ) } Tabs.List = TabsList Tabs.Tab = TabsTab Tabs.Panel = TabsPanel 2. Render Props (for flexible rendering logic) export function DataList<T>({ items, renderItem, renderEmpty }: DataListProps<T>) { if (items.length === 0) return renderEmpty?.() ?? <EmptyState /> return <ul>{items.map((item, i) => <li key={i}>{renderItem(item)}</li>)}</ul> } 3. Higher-Order Components (for cross-cutting concerns β use sparingly) export function withAuth<P>(Component: ComponentType<P>) { return function AuthenticatedComponent(props: P) { const { user, isLoading } = useAuth() if (isLoading) return <Spinner /> if (!user) return <Navigate to="/login" /> return <Component {...props} /> } }
One component per file β always Named exports β never default exports (refactoring safety) Props interface β always explicit, always exported No business logic in components β extract to hooks No inline styles β use Tailwind classes or CSS modules No string refs β useRef only No index as key β use stable identifiers Memo strategically β not everywhere, only for expensive renders Children over props β prefer composition over configuration Accessible by default β semantic HTML, ARIA when needed
Is it server data (from API)? ββ YES β TanStack Query (or SWR) β NEVER Redux/Zustand for server state β ββ NO β Is it shared across features? ββ YES β Is it complex with many actions? β ββ YES β Zustand (or Redux Toolkit if team knows it) β ββ NO β Jotai (atomic) or Zustand (simple store) β ββ NO β Is it shared within a feature? ββ YES β Context + useReducer (or Zustand feature store) ββ NO β useState / useReducer (component-local)
ToolBest ForBundleLearningTeam SizeuseStateComponent-local0 KBNoneAnyuseReducerComplex local state0 KBLowAnyContextFeature-scoped, low-frequency0 KBLowAnyZustandGlobal client state1.1 KBLowAnyJotaiAtomic derived state3.4 KBMediumSmall-MedTanStack QueryServer state12 KBMediumAnyRedux ToolkitComplex global + middleware11 KBHighLarge
// api/users.ts β query key factory pattern export const userKeys = { all: ['users'] as const, lists: () => [...userKeys.all, 'list'] as const, list: (filters: Filters) => [...userKeys.lists(), filters] as const, details: () => [...userKeys.all, 'detail'] as const, detail: (id: string) => [...userKeys.details(), id] as const, } // hooks/useUsers.ts export function useUsers(filters: Filters) { return useQuery({ queryKey: userKeys.list(filters), queryFn: () => fetchUsers(filters), staleTime: 5 * 60 * 1000, // 5 min placeholderData: keepPreviousData, }) } export function useUpdateUser() { const queryClient = useQueryClient() return useMutation({ mutationFn: updateUser, onMutate: async (newUser) => { // Optimistic update await queryClient.cancelQueries({ queryKey: userKeys.detail(newUser.id) }) const previous = queryClient.getQueryData(userKeys.detail(newUser.id)) queryClient.setQueryData(userKeys.detail(newUser.id), newUser) return { previous } }, onError: (err, newUser, context) => { queryClient.setQueryData(userKeys.detail(newUser.id), context?.previous) }, onSettled: (data, err, variables) => { queryClient.invalidateQueries({ queryKey: userKeys.detail(variables.id) }) queryClient.invalidateQueries({ queryKey: userKeys.lists() }) }, }) }
// stores/useUIStore.ts β thin, focused stores interface UIStore { sidebarOpen: boolean theme: 'light' | 'dark' | 'system' toggleSidebar: () => void setTheme: (theme: UIStore['theme']) => void } export const useUIStore = create<UIStore>()( persist( (set) => ({ sidebarOpen: true, theme: 'system', toggleSidebar: () => set((s) => ({ sidebarOpen: !s.sidebarOpen })), setTheme: (theme) => set({ theme }), }), { name: 'ui-preferences' } ) ) // Usage: const theme = useUIStore((s) => s.theme) β always use selectors!
Server state β client state β never mix them in the same store Smallest scope possible β useState > Context > Zustand > Redux No useEffect for derived state β use useMemo or compute inline Selectors always β useStore(s => s.field) not useStore() URL is state β search params, filters, pagination β URL, not React state
// hooks/useDebounce.ts export function useDebounce<T>(value: T, delayMs: number = 300): T { const [debouncedValue, setDebouncedValue] = useState(value) useEffect(() => { const timer = setTimeout(() => setDebouncedValue(value), delayMs) return () => clearTimeout(timer) }, [value, delayMs]) return debouncedValue }
HookPurposeWhen to UseuseDebounceDebounce value changesSearch inputs, resizeuseMediaQueryResponsive breakpointsConditional renderinguseLocalStoragePersistent local statePreferences, draftsuseIntersectionViewport detectionLazy load, infinite scrollusePreviousTrack previous valueAnimations, comparisonsuseClickOutsideDetect outside clicksDropdowns, modalsuseEventListenerSafe event bindingKeyboard, scroll, resizeuseToggleBoolean state toggleModals, accordions
One concern per hook β useUserSearch not useEverything Return tuple or object β tuple for 1-2 values, object for 3+ Accept options object β useDebounce(value, { delay: 300 }) scales better Handle cleanup β every subscription/timer needs cleanup in useEffect return No hooks in conditions β extract conditional logic into the hook body Test hooks independently β use renderHook from testing-library
{ "compilerOptions": { "strict": true, "noUncheckedIndexedAccess": true, "noImplicitOverride": true, "exactOptionalPropertyTypes": true, "forceConsistentCasingInFileNames": true, "paths": { "@/*": ["./src/*"] } } }
// 1. Discriminated unions for state machines type AsyncState<T> = | { status: 'idle' } | { status: 'loading' } | { status: 'success'; data: T } | { status: 'error'; error: Error } // 2. Polymorphic components type ButtonProps<C extends ElementType = 'button'> = { as?: C variant?: 'primary' | 'secondary' } & ComponentPropsWithoutRef<C> export function Button<C extends ElementType = 'button'>({ as, variant = 'primary', ...props }: ButtonProps<C>) { const Component = as || 'button' return <Component {...props} /> } // 3. Branded types for IDs type UserId = string & { __brand: 'UserId' } type PostId = string & { __brand: 'PostId' } // 4. Zod for runtime validation const userSchema = z.object({ id: z.string().uuid(), email: z.string().email(), role: z.enum(['admin', 'user', 'viewer']), }) type User = z.infer<typeof userSchema>
Zero any β use unknown and narrow, or generics Zod at boundaries β validate all external data (API, forms, URL params) Discriminated unions over optional fields β { status: 'success'; data: T } not { data?: T; error?: Error } Branded types for IDs β prevent userId being passed where postId expected Satisfies over as β config satisfies Config preserves inference; as Config lies
MetricTargetMeasurementFirst Contentful Paint< 1.8sLighthouseLargest Contentful Paint< 2.5sLighthouseInteraction to Next Paint< 200msLighthouseCumulative Layout Shift< 0.1LighthouseBundle size (gzipped)< 200 KBwebpack-bundle-analyzerJS execution (main thread)< 3sChrome DevTools
PriorityTechniqueImpactEffortP0Code splitting (route-based)π΄ HighLowP0Image optimization (next/image, srcset)π΄ HighLowP1Tree shaking (named imports)π‘ MediumLowP1Virtualization for long listsπ‘ MediumMediumP1Debounce expensive operationsπ‘ MediumLowP2React.memo on expensive componentsπ’ Low-MedLowP2useMemo/useCallback for expensive calculationsπ’ Low-MedLowP3Web Workers for heavy computationπ’ LowHigh
// 1. Route-based (automatic with Next.js, manual with React Router) const Dashboard = lazy(() => import('./features/dashboard')) const Settings = lazy(() => import('./features/settings')) // 2. Component-based (heavy components) const Chart = lazy(() => import('./components/Chart')) const MarkdownEditor = lazy(() => import('./components/MarkdownEditor').then(m => ({ default: m.MarkdownEditor })) ) // 3. Library-based (heavy third-party) const { PDFViewer } = await import('@react-pdf/renderer')
// With React Compiler enabled, manual memo/useMemo/useCallback become unnecessary // The compiler auto-memoizes. Remove manual optimizations: // β const memoized = useMemo(() => expensiveCalc(data), [data]) // β const memoized = expensiveCalc(data) // compiler handles it // Enable in babel config: // plugins: [['babel-plugin-react-compiler', {}]]
Never create components inside components β define at module level Never create objects/arrays in JSX β style={{ color: 'red' }} rerenders always Children as props prevent rerender β <Layout><ExpensiveChild /></Layout> Key must be stable and unique β not index, not Math.random() Avoid context value churn β memoize provider value or split contexts Profile before optimizing β React DevTools Profiler, not guesswork
// Three levels of error boundaries: // 1. App-level (catches everything, shows full-page error) // 2. Feature-level (isolates feature failures) // 3. Component-level (for risky widgets β charts, third-party) // Modern error boundary with react-error-boundary import { ErrorBoundary, FallbackProps } from 'react-error-boundary' function FeatureErrorFallback({ error, resetErrorBoundary }: FallbackProps) { return ( <div role="alert" className="rounded-lg border-red-200 bg-red-50 p-4"> <h3>Something went wrong</h3> <pre className="text-sm text-red-600">{error.message}</pre> <button onClick={resetErrorBoundary}>Try again</button> </div> ) } // Usage: <ErrorBoundary FallbackComponent={FeatureErrorFallback} onReset={() => queryClient.clear()}> <DashboardFeature /> </ErrorBoundary>
App-level error boundary wrapping entire app Feature-level boundaries for each major feature API errors handled in TanStack Query's onError / error states Form validation errors shown inline (not alerts) 404 page for unknown routes Offline detection and graceful degradation Error reporting to monitoring (Sentry, etc.) User-friendly error messages (no stack traces in production)
LibraryBest ForBundleRendersReact Hook FormMost forms9 KBMinimal (uncontrolled)FormikSimple forms13 KBEvery keystrokeTanStack FormType-safe complex5 KBControlledNative1-2 field forms0 KBYou control Default recommendation: React Hook Form + Zod
const schema = z.object({ email: z.string().email('Invalid email'), password: z.string().min(8, 'Min 8 characters'), role: z.enum(['admin', 'user']), }) type FormData = z.infer<typeof schema> export function LoginForm({ onSubmit }: { onSubmit: (data: FormData) => void }) { const form = useForm<FormData>({ resolver: zodResolver(schema), defaultValues: { email: '', password: '', role: 'user' }, }) return ( <form onSubmit={form.handleSubmit(onSubmit)} noValidate> <label htmlFor="email">Email</label> <input id="email" type="email" {...form.register('email')} aria-invalid={!!form.formState.errors.email} /> {form.formState.errors.email && ( <p role="alert">{form.formState.errors.email.message}</p> )} {/* ... more fields */} <button type="submit" disabled={form.formState.isSubmitting}> {form.formState.isSubmitting ? 'Signing in...' : 'Sign in'} </button> </form> ) }
LevelToolCoverage TargetWhat to TestUnitVitest80% business logicHooks, utilities, reducersComponentTesting LibraryKey user flowsRendering, interactions, a11yIntegrationTesting LibraryFeature flowsMulti-component workflowsE2EPlaywrightCritical pathsAuth, checkout, core flowsVisualChromatic/PercyUI componentsRegression detection
// Component test (Testing Library philosophy: test behavior, not implementation) import { render, screen } from '@testing-library/react' import userEvent from '@testing-library/user-event' describe('UserCard', () => { it('calls onEdit when edit button clicked', async () => { const user = userEvent.setup() const onEdit = vi.fn() render(<UserCard user={mockUser} onEdit={onEdit} />) await user.click(screen.getByRole('button', { name: /edit/i })) expect(onEdit).toHaveBeenCalledWith(mockUser.id) }) it('does not render edit button when onEdit not provided', () => { render(<UserCard user={mockUser} />) expect(screen.queryByRole('button', { name: /edit/i })).not.toBeInTheDocument() }) })
Test behavior, not implementation β never test state directly or useEffect Use accessible queries β getByRole > getByTestId > getByText User events over fireEvent β userEvent.click simulates real interaction One assertion per concept β not one per test, but focused assertions Mock at boundaries β API calls, not internal functions No snapshot tests β they break on every change and test nothing meaningful Arrange-Act-Assert β clear structure in every test
Semantic HTML β <button> not <div onClick>, <nav> not <div class="nav"> Keyboard navigation β every interactive element reachable via Tab, operable via Enter/Space Focus management β visible focus indicator, logical tab order, focus trap in modals Alt text β every <img> has descriptive alt (or alt="" if decorative) Color contrast β 4.5:1 for normal text, 3:1 for large text (WCAG AA) ARIA labels β aria-label for icon-only buttons, aria-describedby for hints Live regions β aria-live="polite" for dynamic content (toasts, form errors) Reduced motion β respect prefers-reduced-motion for animations Screen reader testing β test with VoiceOver (Mac) or NVDA (Windows) Automated scanning β axe-core in CI (vitest-axe or @axe-core/playwright)
TypeScript strict mode, zero errors All tests passing Bundle analyzed, no unexpected large dependencies Error boundaries at app and feature level Environment variables validated at build time Security headers configured (CSP, HSTS, X-Frame-Options) SEO meta tags (title, description, OG tags) Analytics/error monitoring integrated Performance budget met (LCP < 2.5s)
Storybook for component library Visual regression tests a11y automated checks in CI Feature flags for risky features Preview deployments for PRs Bundle size CI check (fail if +10%)
LayerRecommendationAlternativeFrameworkNext.js 15Remix, Vite SPALanguageTypeScript (strict)βStylingTailwind CSS v4CSS ModulesComponentsshadcn/uiRadix, Headless UIState (server)TanStack Query v5SWRState (client)ZustandJotaiFormsReact Hook Form + ZodTanStack FormTestingVitest + Testing LibraryJestE2EPlaywrightCypressLintingBiomeESLint + PrettierAuthAuth.js (NextAuth)Clerk, LuciaDatabaseDrizzle ORMPrismaDeploymentVercelCloudflare, Fly.ioMonitoringSentryDatadog
DimensionWeightWhat to ScoreArchitecture20%Structure, separation, patternsType safety15%Strict TS, zero any, Zod boundariesPerformance15%Core Web Vitals, bundle sizeTesting15%Coverage, quality, pyramidAccessibility10%WCAG AA, keyboard, screen readerState management10%Right tool, no prop drillingError handling10%Boundaries, user-friendly, monitoringDeveloper experience5%Linting, formatting, CI speed Grading: 90+ World-class | 75-89 Production-ready | 60-74 Needs work | <60 Tech debt crisis
#MistakeFix1useEffect for derived stateCompute inline or useMemo2Prop drilling 5+ levels deepContext, Zustand, or composition3Fetching in useEffectTanStack Query or framework loaders4Default exports everywhereNamed exports for refactoring safety5Testing implementation detailsTest behavior with Testing Library6Giant components (500+ lines)Extract hooks and sub-components7No error boundariesAdd at app, feature, and widget level8Redux for server stateTanStack Query for API data9Ignoring a11y until the endBuild accessible from day 110No TypeScript strict modeEnable strict, fix all errors
"Set up a new React project" β Phase 1-2 architecture + structure "Review my component" β Phase 3 rules + quality scoring "Help me choose state management" β Phase 4 decision tree "Optimize performance" β Phase 7 priority stack + profiling "Add error handling" β Phase 8 error boundary architecture "Build a form" β Phase 9 React Hook Form + Zod pattern "Write tests for this component" β Phase 10 testing patterns "Check accessibility" β Phase 11 checklist "Prepare for production" β Phase 12 deployment checklist "Audit my React app" β Full quality scoring across all phases "Migrate from class components" β Modern patterns + hooks "Upgrade to React 19" β Compiler, Server Components, Actions
This skill gives you the methodology. For industry-specific implementation patterns, grab an AfrexAI Context Pack ($47): SaaS Context Pack β SaaS-specific React patterns, billing UI, dashboard architecture Fintech Context Pack β Financial UI patterns, real-time data, compliance Healthcare Context Pack β HIPAA-compliant UI, patient data handling π Browse all 10 packs: https://afrexai-cto.github.io/context-packs/
afrexai-nextjs-production β Next.js production engineering afrexai-vibe-coding β AI-assisted development methodology afrexai-technical-seo β SEO for React SPAs and SSR afrexai-test-automation-engineering β Complete testing strategy afrexai-ui-design-system β Design system architecture
Code helpers, APIs, CLIs, browser automation, testing, and developer operations.
Largest current source with strong distribution and engagement signals.