{"slug":"frontend-patterns","title":"frontend-patterns","summary":"Frontend development patterns for React, Next.js, state management, performance optimization, and UI best practices. Use when building or reviewing React or Next.js components, state, or render performance.","platform":"Claude","tags":[],"authorName":"LLM Mart","authorSlug":"llm-mart","score":0,"source":"github","price":null,"verified":false,"createdAt":"2026-12-02T16:53:39.343373Z","repo":{"url":"https://github.com/beginwithu/agent-skills","stars":11,"forks":2,"license":"MIT","updatedAt":"2026-12-02T16:37:11Z"},"bodyHtml":"<hr>\n<h2>name: frontend-patterns\ndescription: Frontend development patterns for React, Next.js, state management, performance optimization, and UI best practices. Use when building or reviewing React or Next.js components, state, or render performance.\nmetadata:\norigin: ECC</h2>\n<h1>Frontend Development Patterns</h1>\n<p>Modern frontend patterns for React, Next.js, and performant user interfaces.</p>\n<h2>When to Activate</h2>\n<ul>\n<li>Building React components (composition, props, rendering)</li>\n<li>Managing state (useState, useReducer, Zustand, Context)</li>\n<li>Implementing data fetching (SWR, React Query, server components)</li>\n<li>Optimizing performance (memoization, virtualization, code splitting)</li>\n<li>Working with forms (validation, controlled inputs, Zod schemas)</li>\n<li>Handling client-side routing and navigation</li>\n<li>Building accessible, responsive UI patterns</li>\n</ul>\n<h2>Component Patterns</h2>\n<h3>Composition Over Inheritance</h3>\n<pre><code>// PASS: GOOD: Component composition\ninterface CardProps {\n  children: React.ReactNode\n  variant?: 'default' | 'outlined'\n}\n\nexport function Card({ children, variant = 'default' }: CardProps) {\n  return &lt;div className={`card card-${variant}`}&gt;{children}&lt;/div&gt;\n}\n\nexport function CardHeader({ children }: { children: React.ReactNode }) {\n  return &lt;div className=\"card-header\"&gt;{children}&lt;/div&gt;\n}\n\nexport function CardBody({ children }: { children: React.ReactNode }) {\n  return &lt;div className=\"card-body\"&gt;{children}&lt;/div&gt;\n}\n\n// Usage\n&lt;Card&gt;\n  &lt;CardHeader&gt;Title&lt;/CardHeader&gt;\n  &lt;CardBody&gt;Content&lt;/CardBody&gt;\n&lt;/Card&gt;\n</code></pre>\n<h3>Compound Components</h3>\n<pre><code>interface TabsContextValue {\n  activeTab: string\n  setActiveTab: (tab: string) =&gt; void\n}\n\nconst TabsContext = createContext&lt;TabsContextValue | undefined&gt;(undefined)\n\nexport function Tabs({ children, defaultTab }: {\n  children: React.ReactNode\n  defaultTab: string\n}) {\n  const [activeTab, setActiveTab] = useState(defaultTab)\n\n  return (\n    &lt;TabsContext.Provider value={{ activeTab, setActiveTab }}&gt;\n      {children}\n    &lt;/TabsContext.Provider&gt;\n  )\n}\n\nexport function TabList({ children }: { children: React.ReactNode }) {\n  return &lt;div className=\"tab-list\"&gt;{children}&lt;/div&gt;\n}\n\nexport function Tab({ id, children }: { id: string, children: React.ReactNode }) {\n  const context = useContext(TabsContext)\n  if (!context) throw new Error('Tab must be used within Tabs')\n\n  return (\n    &lt;button\n      className={context.activeTab === id ? 'active' : ''}\n      onClick={() =&gt; context.setActiveTab(id)}\n    &gt;\n      {children}\n    &lt;/button&gt;\n  )\n}\n\n// Usage\n&lt;Tabs defaultTab=\"overview\"&gt;\n  &lt;TabList&gt;\n    &lt;Tab id=\"overview\"&gt;Overview&lt;/Tab&gt;\n    &lt;Tab id=\"details\"&gt;Details&lt;/Tab&gt;\n  &lt;/TabList&gt;\n&lt;/Tabs&gt;\n</code></pre>\n<h3>Render Props Pattern</h3>\n<pre><code>interface DataLoaderProps&lt;T&gt; {\n  url: string\n  children: (data: T | null, loading: boolean, error: Error | null) =&gt; React.ReactNode\n}\n\nexport function DataLoader&lt;T&gt;({ url, children }: DataLoaderProps&lt;T&gt;) {\n  const [data, setData] = useState&lt;T | null&gt;(null)\n  const [loading, setLoading] = useState(true)\n  const [error, setError] = useState&lt;Error | null&gt;(null)\n\n  useEffect(() =&gt; {\n    fetch(url)\n      .then(res =&gt; res.json())\n      .then(setData)\n      .catch(setError)\n      .finally(() =&gt; setLoading(false))\n  }, [url])\n\n  return &lt;&gt;{children(data, loading, error)}&lt;/&gt;\n}\n\n// Usage\n&lt;DataLoader&lt;Market[]&gt; url=\"/api/markets\"&gt;\n  {(markets, loading, error) =&gt; {\n    if (loading) return &lt;Spinner /&gt;\n    if (error) return &lt;Error error={error} /&gt;\n    return &lt;MarketList markets={markets!} /&gt;\n  }}\n&lt;/DataLoader&gt;\n</code></pre>\n<h2>Custom Hooks Patterns</h2>\n<h3>State Management Hook</h3>\n<pre><code>export function useToggle(initialValue = false): [boolean, () =&gt; void] {\n  const [value, setValue] = useState(initialValue)\n\n  const toggle = useCallback(() =&gt; {\n    setValue(v =&gt; !v)\n  }, [])\n\n  return [value, toggle]\n}\n\n// Usage\nconst [isOpen, toggleOpen] = useToggle()\n</code></pre>\n<h3>Async Data Fetching Hook</h3>\n<pre><code>interface UseQueryOptions&lt;T&gt; {\n  onSuccess?: (data: T) =&gt; void\n  onError?: (error: Error) =&gt; void\n  enabled?: boolean\n}\n\nexport function useQuery&lt;T&gt;(\n  key: string,\n  fetcher: () =&gt; Promise&lt;T&gt;,\n  options?: UseQueryOptions&lt;T&gt;\n) {\n  const [data, setData] = useState&lt;T | null&gt;(null)\n  const [error, setError] = useState&lt;Error | null&gt;(null)\n  const [loading, setLoading] = useState(false)\n\n  // Keep the latest fetcher/options in refs so refetch stays referentially\n  // stable even when callers pass inline functions and object literals.\n  // Without this, every render creates a new refetch, and the effect below\n  // re-runs after each state update - an infinite fetch loop.\n  const fetcherRef = useRef(fetcher)\n  const optionsRef = useRef(options)\n  useEffect(() =&gt; {\n    fetcherRef.current = fetcher\n    optionsRef.current = options\n  })\n\n  const refetch = useCallback(async () =&gt; {\n    setLoading(true)\n    setError(null)\n\n    try {\n      const result = await fetcherRef.current()\n      setData(result)\n      optionsRef.current?.onSuccess?.(result)\n    } catch (err) {\n      const error = err as Error\n      setError(error)\n      optionsRef.current?.onError?.(error)\n    } finally {\n      setLoading(false)\n    }\n  }, [])\n\n  const enabled = options?.enabled !== false\n\n  useEffect(() =&gt; {\n    if (enabled) {\n      refetch()\n    }\n  }, [key, enabled, refetch])\n\n  return { data, error, loading, refetch }\n}\n\n// Usage\nconst { data: markets, loading, error, refetch } = useQuery(\n  'markets',\n  () =&gt; fetch('/api/markets').then(r =&gt; r.json()),\n  {\n    onSuccess: data =&gt; console.log('Fetched', data.length, 'markets'),\n    onError: err =&gt; console.error('Failed:', err)\n  }\n)\n</code></pre>\n<h3>Debounce Hook</h3>\n<pre><code>export function useDebounce&lt;T&gt;(value: T, delay: number): T {\n  const [debouncedValue, setDebouncedValue] = useState&lt;T&gt;(value)\n\n  useEffect(() =&gt; {\n    const handler = setTimeout(() =&gt; {\n      setDebouncedValue(value)\n    }, delay)\n\n    return () =&gt; clearTimeout(handler)\n  }, [value, delay])\n\n  return debouncedValue\n}\n\n// Usage\nconst [searchQuery, setSearchQuery] = useState('')\nconst debouncedQuery = useDebounce(searchQuery, 500)\n\nuseEffect(() =&gt; {\n  if (debouncedQuery) {\n    performSearch(debouncedQuery)\n  }\n}, [debouncedQuery])\n</code></pre>\n<h2>State Management Patterns</h2>\n<h3>Context + Reducer Pattern</h3>\n<pre><code>interface State {\n  markets: Market[]\n  selectedMarket: Market | null\n  loading: boolean\n}\n\ntype Action =\n  | { type: 'SET_MARKETS'; payload: Market[] }\n  | { type: 'SELECT_MARKET'; payload: Market }\n  | { type: 'SET_LOADING'; payload: boolean }\n\nfunction reducer(state: State, action: Action): State {\n  switch (action.type) {\n    case 'SET_MARKETS':\n      return { ...state, markets: action.payload }\n    case 'SELECT_MARKET':\n      return { ...state, selectedMarket: action.payload }\n    case 'SET_LOADING':\n      return { ...state, loading: action.payload }\n    default:\n      return state\n  }\n}\n\nconst MarketContext = createContext&lt;{\n  state: State\n  dispatch: Dispatch&lt;Action&gt;\n} | undefined&gt;(undefined)\n\nexport function MarketProvider({ children }: { children: React.ReactNode }) {\n  const [state, dispatch] = useReducer(reducer, {\n    markets: [],\n    selectedMarket: null,\n    loading: false\n  })\n\n  return (\n    &lt;MarketContext.Provider value={{ state, dispatch }}&gt;\n      {children}\n    &lt;/MarketContext.Provider&gt;\n  )\n}\n\nexport function useMarkets() {\n  const context = useContext(MarketContext)\n  if (!context) throw new Error('useMarkets must be used within MarketProvider')\n  return context\n}\n</code></pre>\n<h2>Performance Optimization</h2>\n<h3>Memoization</h3>\n<pre><code>// PASS: useMemo for expensive computations\n// Copy before sorting - Array.prototype.sort mutates in place\nconst sortedMarkets = useMemo(() =&gt; {\n  return [...markets].sort((a, b) =&gt; b.volume - a.volume)\n}, [markets])\n\n// PASS: useCallback for functions passed to children\nconst handleSearch = useCallback((query: string) =&gt; {\n  setSearchQuery(query)\n}, [])\n\n// PASS: React.memo for pure components\nexport const MarketCard = React.memo&lt;MarketCardProps&gt;(({ market }) =&gt; {\n  return (\n    &lt;div className=\"market-card\"&gt;\n      &lt;h3&gt;{market.name}&lt;/h3&gt;\n      &lt;p&gt;{market.description}&lt;/p&gt;\n    &lt;/div&gt;\n  )\n})\n</code></pre>\n<h3>Code Splitting &amp; Lazy Loading</h3>\n<pre><code>import { lazy, Suspense } from 'react'\n\n// PASS: Lazy load heavy components\nconst HeavyChart = lazy(() =&gt; import('./HeavyChart'))\nconst ThreeJsBackground = lazy(() =&gt; import('./ThreeJsBackground'))\n\nexport function Dashboard() {\n  return (\n    &lt;div&gt;\n      &lt;Suspense fallback={&lt;ChartSkeleton /&gt;}&gt;\n        &lt;HeavyChart data={data} /&gt;\n      &lt;/Suspense&gt;\n\n      &lt;Suspense fallback={null}&gt;\n        &lt;ThreeJsBackground /&gt;\n      &lt;/Suspense&gt;\n    &lt;/div&gt;\n  )\n}\n</code></pre>\n<h3>Virtualization for Long Lists</h3>\n<pre><code>import { useVirtualizer } from '@tanstack/react-virtual'\n\nexport function VirtualMarketList({ markets }: { markets: Market[] }) {\n  const parentRef = useRef&lt;HTMLDivElement&gt;(null)\n\n  const virtualizer = useVirtualizer({\n    count: markets.length,\n    getScrollElement: () =&gt; parentRef.current,\n    estimateSize: () =&gt; 100,  // Estimated row height\n    overscan: 5  // Extra items to render\n  })\n\n  return (\n    &lt;div ref={parentRef} style={{ height: '600px', overflow: 'auto' }}&gt;\n      &lt;div\n        style={{\n          height: `${virtualizer.getTotalSize()}px`,\n          position: 'relative'\n        }}\n      &gt;\n        {virtualizer.getVirtualItems().map(virtualRow =&gt; (\n          &lt;div\n            key={virtualRow.index}\n            style={{\n              position: 'absolute',\n              top: 0,\n              left: 0,\n              width: '100%',\n              height: `${virtualRow.size}px`,\n              transform: `translateY(${virtualRow.start}px)`\n            }}\n          &gt;\n            &lt;MarketCard market={markets[virtualRow.index]} /&gt;\n          &lt;/div&gt;\n        ))}\n      &lt;/div&gt;\n    &lt;/div&gt;\n  )\n}\n</code></pre>\n<h2>Form Handling Patterns</h2>\n<h3>Controlled Form with Validation</h3>\n<pre><code>interface FormData {\n  name: string\n  description: string\n  endDate: string\n}\n\ninterface FormErrors {\n  name?: string\n  description?: string\n  endDate?: string\n}\n\nexport function CreateMarketForm() {\n  const [formData, setFormData] = useState&lt;FormData&gt;({\n    name: '',\n    description: '',\n    endDate: ''\n  })\n\n  const [errors, setErrors] = useState&lt;FormErrors&gt;({})\n\n  const validate = (): boolean =&gt; {\n    const newErrors: FormErrors = {}\n\n    if (!formData.name.trim()) {\n      newErrors.name = 'Name is required'\n    } else if (formData.name.length &gt; 200) {\n      newErrors.name = 'Name must be under 200 characters'\n    }\n\n    if (!formData.description.trim()) {\n      newErrors.description = 'Description is required'\n    }\n\n    if (!formData.endDate) {\n      newErrors.endDate = 'End date is required'\n    }\n\n    setErrors(newErrors)\n    return Object.keys(newErrors).length === 0\n  }\n\n  const handleSubmit = async (e: React.FormEvent) =&gt; {\n    e.preventDefault()\n\n    if (!validate()) return\n\n    try {\n      await createMarket(formData)\n      // Success handling\n    } catch (error) {\n      // Error handling\n    }\n  }\n\n  return (\n    &lt;form onSubmit={handleSubmit}&gt;\n      &lt;input\n        value={formData.name}\n        onChange={e =&gt; setFormData(prev =&gt; ({ ...prev, name: e.target.value }))}\n        placeholder=\"Market name\"\n      /&gt;\n      {errors.name &amp;&amp; &lt;span className=\"error\"&gt;{errors.name}&lt;/span&gt;}\n\n      {/* Other fields */}\n\n      &lt;button type=\"submit\"&gt;Create Market&lt;/button&gt;\n    &lt;/form&gt;\n  )\n}\n</code></pre>\n<h2>Error Boundary Pattern</h2>\n<pre><code>interface ErrorBoundaryState {\n  hasError: boolean\n  error: Error | null\n}\n\nexport class ErrorBoundary extends React.Component&lt;\n  { children: React.ReactNode },\n  ErrorBoundaryState\n&gt; {\n  state: ErrorBoundaryState = {\n    hasError: false,\n    error: null\n  }\n\n  static getDerivedStateFromError(error: Error): ErrorBoundaryState {\n    return { hasError: true, error }\n  }\n\n  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {\n    console.error('Error boundary caught:', error, errorInfo)\n  }\n\n  render() {\n    if (this.state.hasError) {\n      return (\n        &lt;div className=\"error-fallback\"&gt;\n          &lt;h2&gt;Something went wrong&lt;/h2&gt;\n          &lt;p&gt;{this.state.error?.message}&lt;/p&gt;\n          &lt;button onClick={() =&gt; this.setState({ hasError: false })}&gt;\n            Try again\n          &lt;/button&gt;\n        &lt;/div&gt;\n      )\n    }\n\n    return this.props.children\n  }\n}\n\n// Usage\n&lt;ErrorBoundary&gt;\n  &lt;App /&gt;\n&lt;/ErrorBoundary&gt;\n</code></pre>\n<h2>Animation Patterns</h2>\n<h3>Framer Motion Animations</h3>\n<pre><code>import { motion, AnimatePresence } from 'framer-motion'\n\n// PASS: List animations\nexport function AnimatedMarketList({ markets }: { markets: Market[] }) {\n  return (\n    &lt;AnimatePresence&gt;\n      {markets.map(market =&gt; (\n        &lt;motion.div\n          key={market.id}\n          initial={{ opacity: 0, y: 20 }}\n          animate={{ opacity: 1, y: 0 }}\n          exit={{ opacity: 0, y: -20 }}\n          transition={{ duration: 0.3 }}\n        &gt;\n          &lt;MarketCard market={market} /&gt;\n        &lt;/motion.div&gt;\n      ))}\n    &lt;/AnimatePresence&gt;\n  )\n}\n\n// PASS: Modal animations\nexport function Modal({ isOpen, onClose, children }: ModalProps) {\n  return (\n    &lt;AnimatePresence&gt;\n      {isOpen &amp;&amp; (\n        &lt;&gt;\n          &lt;motion.div\n            className=\"modal-overlay\"\n            initial={{ opacity: 0 }}\n            animate={{ opacity: 1 }}\n            exit={{ opacity: 0 }}\n            onClick={onClose}\n          /&gt;\n          &lt;motion.div\n            className=\"modal-content\"\n            initial={{ opacity: 0, scale: 0.9, y: 20 }}\n            animate={{ opacity: 1, scale: 1, y: 0 }}\n            exit={{ opacity: 0, scale: 0.9, y: 20 }}\n          &gt;\n            {children}\n          &lt;/motion.div&gt;\n        &lt;/&gt;\n      )}\n    &lt;/AnimatePresence&gt;\n  )\n}\n</code></pre>\n<h2>Accessibility Patterns</h2>\n<h3>Keyboard Navigation</h3>\n<pre><code>export function Dropdown({ options, onSelect }: DropdownProps) {\n  const [isOpen, setIsOpen] = useState(false)\n  const [activeIndex, setActiveIndex] = useState(0)\n\n  const handleKeyDown = (e: React.KeyboardEvent) =&gt; {\n    switch (e.key) {\n      case 'ArrowDown':\n        e.preventDefault()\n        setActiveIndex(i =&gt; Math.min(i + 1, options.length - 1))\n        break\n      case 'ArrowUp':\n        e.preventDefault()\n        setActiveIndex(i =&gt; Math.max(i - 1, 0))\n        break\n      case 'Enter':\n        e.preventDefault()\n        onSelect(options[activeIndex])\n        setIsOpen(false)\n        break\n      case 'Escape':\n        setIsOpen(false)\n        break\n    }\n  }\n\n  return (\n    &lt;div\n      role=\"combobox\"\n      aria-expanded={isOpen}\n      aria-haspopup=\"listbox\"\n      onKeyDown={handleKeyDown}\n    &gt;\n      {/* Dropdown implementation */}\n    &lt;/div&gt;\n  )\n}\n</code></pre>\n<h3>Focus Management</h3>\n<pre><code>export function Modal({ isOpen, onClose, children }: ModalProps) {\n  const modalRef = useRef&lt;HTMLDivElement&gt;(null)\n  const previousFocusRef = useRef&lt;HTMLElement | null&gt;(null)\n\n  useEffect(() =&gt; {\n    if (isOpen) {\n      // Save currently focused element\n      previousFocusRef.current = document.activeElement as HTMLElement\n\n      // Focus modal\n      modalRef.current?.focus()\n    } else {\n      // Restore focus when closing\n      previousFocusRef.current?.focus()\n    }\n  }, [isOpen])\n\n  return isOpen ? (\n    &lt;div\n      ref={modalRef}\n      role=\"dialog\"\n      aria-modal=\"true\"\n      tabIndex={-1}\n      onKeyDown={e =&gt; e.key === 'Escape' &amp;&amp; onClose()}\n    &gt;\n      {children}\n    &lt;/div&gt;\n  ) : null\n}\n</code></pre>\n<p><strong>Remember</strong>: Modern frontend patterns enable maintainable, performant user interfaces. Choose patterns that fit your project complexity.</p>\n","files":[{"path":"LICENSE","sizeBytes":1071,"isText":false},{"path":"SKILL.md","sizeBytes":15432,"isText":true}],"reviewScore":null,"reviewSummary":null,"trust":{"provenance":"trusted-source-unreviewed","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow.","bodySource":null},"bodyLocked":false,"purchaseUrl":null,"sourceUrl":null,"report":{"provenance":"trusted-source-unreviewed","screen":{"ran":true,"outcome":"clean","suspicious":0,"notes":0,"hiddenCharacters":false},"virusScan":{"engine":"clamav","status":"clean","scannedAt":"2026-12-02T16:57:11.532743Z","sha256":"CF322F29A15A77CE1B9204A2FF9974A90F603BD18151DABEDAA95DDF90F3FF34","sizeBytes":5785},"review":null,"source":{"repositoryUrl":"https://github.com/beginwithu/agent-skills","path":"skills/frontend-patterns","license":"MIT","commit":"a960304c52212f2e845067047f5cefc0c594d787","subtreeSha":"29E08D3EED3E33A7937D3C746D4EF65FB988AFB8B4FDDA89D61FDC9C7FC864BC","lastSyncedAt":"2026-12-02T16:52:59.20206Z"},"reviewedAt":"2026-12-02T17:03:54.983141Z","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow."},"install":[{"target":"skills-cli","command":"npx skills add https://github.com/beginwithu/agent-skills/tree/main/skills/frontend-patterns"},{"target":"claude-code","command":"claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install beginwithu-agent-skills@llmmart"},{"target":"git","command":"git clone https://github.com/beginwithu/agent-skills.git"}]}