Ultimate React Patterns
Comprehensive skill designed for modern, react, patterns, principles. Includes structured workflows, validation checks, and reusable patterns for development.
Ultimate React Patterns
A definitive skill for production-ready React patterns including server components, streaming SSR, optimistic updates, and advanced composition techniques. Focuses on architectural patterns that scale from small apps to large codebases.
When to Use This Skill
Choose this skill when:
- Architecting component hierarchies for large-scale React applications
- Implementing server components and streaming rendering strategies
- Designing reusable component libraries with flexible APIs
- Building data-driven UIs with optimistic updates and real-time sync
- Establishing team-wide patterns for consistency across a codebase
Consider alternatives when:
- Learning React fundamentals → use a comprehensive React module
- Working on a single small component → inline patterns are sufficient
- Building a design system → use a design system skill
- Need state management only → use a state management skill
Quick Start
# Set up a React project with TypeScript npx create-next-app@latest my-app --typescript --app cd my-app
// Compound component pattern — flexible, composable API interface SelectContextType { value: string; onChange: (value: string) => void; } const SelectContext = createContext<SelectContextType | null>(null); function Select({ children, value, onChange }: { children: ReactNode; value: string; onChange: (value: string) => void; }) { return ( <SelectContext.Provider value={{ value, onChange }}> <div role="listbox">{children}</div> </SelectContext.Provider> ); } function Option({ value, children }: { value: string; children: ReactNode }) { const ctx = useContext(SelectContext)!; return ( <button role="option" aria-selected={ctx.value === value} onClick={() => ctx.onChange(value)} > {children} </button> ); } Select.Option = Option;
Core Concepts
Pattern Decision Matrix
| Pattern | Complexity | Flexibility | Use Case |
|---|---|---|---|
| Props drilling | Low | Low | Shallow trees, 1-2 levels |
| Compound components | Medium | High | Related UI elements with shared state |
| Render props | Medium | Very high | Delegation of rendering logic |
| Custom hooks | Low-Medium | High | Reusable stateful logic |
| HOCs | Medium | Medium | Cross-cutting concerns (auth, logging) |
| Context + Reducer | Medium | High | Feature-level state management |
Optimistic Update Pattern
function useOptimisticUpdate<T>( currentData: T[], updateFn: (item: T) => Promise<T> ) { const [optimisticData, setOptimisticData] = useState(currentData); useEffect(() => { setOptimisticData(currentData); }, [currentData]); const optimisticUpdate = async (item: T, optimisticValue: T) => { // Immediately show optimistic value setOptimisticData(prev => prev.map(d => d === item ? optimisticValue : d) ); try { await updateFn(optimisticValue); } catch { // Revert on failure setOptimisticData(currentData); } }; return { data: optimisticData, optimisticUpdate }; }
Polymorphic Component Pattern
// Component that renders as any HTML element or React component type PolymorphicProps<E extends React.ElementType> = { as?: E; children: React.ReactNode; } & Omit<React.ComponentPropsWithoutRef<E>, 'as' | 'children'>; function Box<E extends React.ElementType = 'div'>({ as, children, ...props }: PolymorphicProps<E>) { const Component = as || 'div'; return <Component {...props}>{children}</Component>; } // Usage: <Box as="section">, <Box as={Link} href="/about">
Configuration
| Parameter | Type | Default | Description |
|---|---|---|---|
componentNaming | string | 'PascalCase' | Naming convention for components |
hookPrefix | string | 'use' | Required prefix for custom hooks |
stateManagement | string | 'context-reducer' | Default state pattern for features |
optimisticUpdates | boolean | true | Enable optimistic UI by default |
componentSplitSize | number | 150 | Max lines before suggesting extraction |
typeStrategy | string | 'interfaces' | Use interfaces vs type aliases |
Best Practices
-
Use the compound component pattern for related UI elements — Instead of passing render configs as props, expose child components that share state through context. This gives consumers full control over rendering order and composition.
-
Implement the state reducer pattern for customizable hooks — Let consumers override state transitions by accepting an optional reducer parameter. This makes hooks extensible without adding more configuration props.
-
Separate data fetching from presentation — Keep components that fetch data distinct from those that render it. This makes presentation components reusable and testable without mocking network requests.
-
Use discriminated unions for component variants — Instead of multiple boolean props (
isLoading,isError,isEmpty), define a single status field with union types. This prevents impossible states like{ isLoading: true, isError: true }. -
Colocate related code in feature directories — Group components, hooks, types, and tests by feature rather than by file type. A developer working on "checkout" should find everything in one directory.
Common Issues
Compound components break with wrapper elements — When a consumer wraps child components in a <div>, the parent can't find them via React.Children. Use context instead of Children.map for compound components — context works regardless of DOM nesting depth.
TypeScript generics lost through HOCs — Higher-order components often strip generic type parameters from wrapped components. Prefer custom hooks over HOCs for logic reuse, or use the forwardRef pattern with explicit generic forwarding when HOCs are necessary.
Render prop callback identity changes every render — Inline render prop functions create new references each render, causing memoized children to re-render. Extract the render callback to a named component or stabilize it with useCallback when this causes measurable performance issues.
Reviews
No reviews yet. Be the first to review this template!
Similar Templates
Full-Stack Code Reviewer
Comprehensive code review skill that checks for security vulnerabilities, performance issues, accessibility, and best practices across frontend and backend code.
Test Suite Generator
Generates comprehensive test suites with unit tests, integration tests, and edge cases. Supports Jest, Vitest, Pytest, and Go testing.
Pro Architecture Workspace
Battle-tested skill for architectural, decision, making, framework. Includes structured workflows, validation checks, and reusable patterns for development.