U

Ultimate React Patterns

Comprehensive skill designed for modern, react, patterns, principles. Includes structured workflows, validation checks, and reusable patterns for development.

SkillClipticsdevelopmentv1.0.0MIT
0 views0 copies

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

PatternComplexityFlexibilityUse Case
Props drillingLowLowShallow trees, 1-2 levels
Compound componentsMediumHighRelated UI elements with shared state
Render propsMediumVery highDelegation of rendering logic
Custom hooksLow-MediumHighReusable stateful logic
HOCsMediumMediumCross-cutting concerns (auth, logging)
Context + ReducerMediumHighFeature-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

ParameterTypeDefaultDescription
componentNamingstring'PascalCase'Naming convention for components
hookPrefixstring'use'Required prefix for custom hooks
stateManagementstring'context-reducer'Default state pattern for features
optimisticUpdatesbooleantrueEnable optimistic UI by default
componentSplitSizenumber150Max lines before suggesting extraction
typeStrategystring'interfaces'Use interfaces vs type aliases

Best Practices

  1. 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.

  2. 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.

  3. 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.

  4. 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 }.

  5. 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.

Community

Reviews

Write a review

No reviews yet. Be the first to review this template!

Similar Templates