Communitygithub.com

フロントエンド開発パターン

React、Next.js、状態管理、パフォーマンス最適化、UIのベストプラクティスのためのフロントエンド開発パターン集。ReactまたはNext.jsのコンポーネント、状態、レンダリングパフォーマンスを構築・レビューする際に使用します。

フロントエンド開発パターン とは?

このスキルは、React、Next.js、および高性能なユーザーインターフェースのための最新のフロントエンドパターンを網羅した総合ガイドです。コンポーネント構成、カスタムフック、状態管理、パフォーマンス最適化、フォーム処理、アニメーション、アクセシビリティなど、幅広いトピックをカバーしています。各パターンには具体的なTypeScriptコード例が含まれており、開発者はベストプラクティスに従ったコンポーネントを効率的に構築できます。また、メモ化、コード分割、仮想化などのパフォーマンス最適化テクニックや、Framer Motionを使ったアニメーションパターン、キーボードナビゲーションなどのアクセシビリティパターンも提供します。このスキルは、AIエージェントアシスタント(Claude Codeなど)と併用して、フロントエンドコードの生成やレビューを行う際に特に有用です。

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/frontend-patterns

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

フロントエンド開発パターン は何をしますか?

React、Next.js、および高性能なユーザーインターフェースのための最新のフロントエンドパターン。

有効化するタイミング

  • Reactコンポーネントの構築(構成、プロパティ、レンダリング)
  • 状態管理(useState、useReducer、Zustand、Context)
  • データフェッチの実装(SWR、React Query、サーバーコンポーネント)
  • パフォーマンス最適化(メモ化、仮想化、コード分割)
  • フォームの処理(バリデーション、制御された入力、Zodスキーマ)
  • クライアントサイドルーティングとナビゲーションの処理
  • アクセシブルでレスポンシブなUIパターンの構築

コンポーネントパターン

継承よりも構成

// PASS: 良い例:コンポーネント構成
interface CardProps {
  children: React.ReactNode
  variant?: 'default' | 'outlined'
}

export function Card({ children, variant = 'default' }: CardProps) {
  return <div className={`card card-${variant}`}>{children}</div>
}

export function CardHeader({ children }: { children: React.ReactNode }) {
  return <div className="card-header">{children}</div>
}

export function CardBody({ children }: { children: React.ReactNode }) {
  return <div className="card-body">{children}</div>
}

// 使用例
<Card>
  <CardHeader>タイトル</CardHeader>
  <CardBody>コンテンツ</CardBody>
</Card>

複合コンポーネント

interface TabsContextValue {
  activeTab: string
  setActiveTab: (tab: string) => void
}

const TabsContext = createContext<TabsContextValue | undefined>(undefined)

export function Tabs({ children, defaultTab }: {
  children: React.ReactNode
  defaultTab: string
}) {
  const [activeTab, setActiveTab] = useState(defaultTab)

  return (
    <TabsContext.Provider value={{ activeTab, setActiveTab }}>
      {children}
    </TabsContext.Provider>
  )
}

export function TabList({ children }: { children: React.ReactNode }) {
  return <div className="tab-list">{children}</div>
}

export function Tab({ id, children }: { id: string, children: React.ReactNode }) {
  const context = useContext(TabsContext)
  if (!context) throw new Error('Tab must be used within Tabs')

  return (
    <button
      className={context.activeTab === id ? 'active' : ''}
      onClick={() => context.setActiveTab(id)}
    >
      {children}
    </button>
  )
}

// 使用例
<Tabs defaultTab="overview">
  <TabList>
    <Tab id="overview">概要</Tab>
    <Tab id="details">詳細</Tab>
  </TabList>
</Tabs>

レンダープロップパターン

interface DataLoaderProps<T> {
  url: string
  children: (data: T | null, loading: boolean, error: Error | null) => React.ReactNode
}

export function DataLoader<T>({ url, children }: DataLoaderProps<T>) {
  const [data, setData] = useState<T | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<Error | null>(null)

  useEffect(() => {
    fetch(url)
      .then(res => res.json())
      .then(setData)
      .catch(setError)
      .finally(() => setLoading(false))
  }, [url])

  return <>{children(data, loading, error)}</>
}

// 使用例
<DataLoader<Market[]> url="/api/markets">
  {(markets, loading, error) => {
    if (loading) return <Spinner />
    if (error) return <Error error={error} />
    return <MarketList markets={markets!} />
  }}
</DataLoader>

カスタムフックパターン

状態管理フック

export function useToggle(initialValue = false): [boolean, () => void] {
  const [value, setValue] = useState(initialValue)

  const toggle = useCallback(() => {
    setValue(v => !v)
  }, [])

  return [value, toggle]
}

// 使用例
const [isOpen, toggleOpen] = useToggle()

非同期データフェッチフック

interface UseQueryOptions<T> {
  onSuccess?: (data: T) => void
  onError?: (error: Error) => void
  enabled?: boolean
}

export function useQuery<T>(
  key: string,
  fetcher: () => Promise<T>,
  options?: UseQueryOptions<T>
) {
  const [data, setData] = useState<T | null>(null)
  const [error, setError] = useState<Error | null>(null)
  const [loading, setLoading] = useState(false)

  // 最新のfetcher/optionsをrefに保持し、呼び出し元がインライン関数やオブジェクトリテラルを渡しても
  // refetchが参照的に安定するようにする。
  // これがないと、レンダリングのたびに新しいrefetchが作成され、以下のエフェクトが
  // 状態更新のたびに再実行され、無限フェッチループが発生する。
  const fetcherRef = useRef(fetcher)
  const optionsRef = useRef(options)
  useEffect(() => {
    fetcherRef.current = fetcher
    optionsRef.current = options
  })

  const refetch = useCallback(async () => {
    setLoading(true)
    setError(null)

    try {
      const result = await fetcherRef.current()
      setData(result)
      optionsRef.current?.onSuccess?.(result)
    } catch (err) {
      const error = err as Error
      setError(error)
      optionsRef.current?.onError?.(error)
    } finally {
      setLoading(false)
    }
  }, [])

  const enabled = options?.enabled !== false

  useEffect(() => {
    if (enabled) {
      refetch()
    }
  }, [key, enabled, refetch])

  return { data, error, loading, refetch }
}

// 使用例
const { data: markets, loading, error, refetch } = useQuery(
  'markets',
  () => fetch('/api/markets').then(r => r.json()),
  {
    onSuccess: data => console.log('Fetched', data.length, 'markets'),
    onError: err => console.error('Failed:', err)
  }
)

デバウンスフック

export function useDebounce<T>(value: T, delay: number): T {
  const [debouncedValue, setDebouncedValue] = useState<T>(value)

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value)
    }, delay)

    return () => clearTimeout(handler)
  }, [value, delay])

  return debouncedValue
}

// 使用例
const [searchQuery, setSearchQuery] = useState('')
const debouncedQuery = useDebounce(searchQuery, 500)

useEffect(() => {
  if (debouncedQuery) {
    performSearch(debouncedQuery)
  }
}, [debouncedQuery])

状態管理パターン

Context + Reducer パターン

interface State {
  markets: Market[]
  selectedMarket: Market | null
  loading: boolean
}

type Action =
  | { type: 'SET_MARKETS'; payload: Market[] }
  | { type: 'SELECT_MARKET'; payload: Market }
  | { type: 'SET_LOADING'; payload: boolean }

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case 'SET_MARKETS':
      return { ...state, markets: action.payload }
    case 'SELECT_MARKET':
      return { ...state, selectedMarket: action.payload }
    case 'SET_LOADING':
      return { ...state, loading: action.payload }
    default:
      return state
  }
}

const MarketContext = createContext<{
  state: State
  dispatch: Dispatch<Action>
} | undefined>(undefined)

export function MarketProvider({ children }: { children: React.ReactNode }) {
  const [state, dispatch] = useReducer(reducer, {
    markets: [],
    selectedMarket: null,
    loading: false
  })

  return (
    <MarketContext.Provider value={{ state, dispatch }}>
      {children}
    </MarketContext.Provider>
  )
}

export function useMarkets() {
  const context = useContext(MarketContext)
  if (!context) throw new Error('useMarkets must be used within MarketProvider')
  return context
}

パフォーマンス最適化

メモ化

// PASS: 高負荷な計算にはuseMemoを使用
// ソート前にコピー - Array.prototype.sortは元の配列を変更する
const sortedMarkets = useMemo(() => {
  return [...markets].sort((a, b) => b.volume - a.volume)
}, [markets])

// PASS: 子コンポーネントに渡す関数にはuseCallbackを使用
const handleSearch = useCallback((query: string) => {
  setSearchQuery(query)
}, [])

// PASS: 純粋なコンポーネントにはReact.memoを使用
export const MarketCard = React.memo<MarketCardProps>(({ market }) => {
  return (
    <div className="market-card">
      <h3>{market.name}</h3>
      <p>{market.description}</p>
    </div>
  )
})

コード分割と遅延読み込み

import { lazy, Suspense } from 'react'

// PASS: 重いコンポーネントは遅延読み込み
const HeavyChart = lazy(() => import('./HeavyChart'))
const ThreeJsBackground = lazy(() => import('./ThreeJsBackground'))

export function Dashboard() {
  return (
    <div>
      <Suspense fallback={<ChartSkeleton />}>
        <HeavyChart data={data} />
      </Suspense>

      <Suspense fallback={null}>
        <ThreeJsBackground />
      </Suspense>
    </div>
  )
}

長いリストの仮想化

import { useVirtualizer } from '@tanstack/react-virtual'

export function VirtualMarketList({ markets }: { markets: Market[] }) {
  const parentRef = useRef<HTMLDivElement>(null)

  const virtualizer = useVirtualizer({
    count: markets.length,
    getScrollElement: () => parentRef.current,
    estimateSize: () => 100,  // 推定行の高さ
    overscan: 5  // 追加でレンダリングするアイテム数
  })

  return (
    <div ref={parentRef} style={{ height: '600px', overflow: 'auto' }}>
      <div
        style={{
          height: `${virtualizer.getTotalSize()}px`,
          position: 'relative'
        }}
      >
        {virtualizer.getVirtualItems().map(virtualRow => (
          <div
            key={virtualRow.index}
            style={{
              position: 'absolute',
              top: 0,
              left: 0,
              width: '100%',
              height: `${virtualRow.size}px`,
              transform: `translateY(${virtualRow.start}px)`
            }}
          >
            <MarketCard market={markets[virtualRow.index]} />
          </div>
        ))}
      </div>
    </div>
  )
}

フォーム処理パターン

バリデーション付き制御フォーム

interface FormData {
  name: string
  description: string
  endDate: string
}

interface FormErrors {
  name?: string
  description?: string
  endDate?: string
}

export function CreateMarketForm() {
  const [formData, setFormData] = useState<FormData>({
    name: '',
    description: '',
    endDate: ''
  })

  const [errors, setErrors] = useState<FormErrors>({})

  const validate = (): boolean => {
    const newErrors: FormErrors = {}

    if (!formData.name.trim()) {
      newErrors.name = '名前は必須です'
    } else if (formData.name.length > 200) {
      newErrors.name = '名前は200文字以内にしてください'
    }

    if (!formData.description.trim()) {
      newErrors.description = '説明は必須です'
    }

    if (!formData.endDate) {
      newErrors.endDate = '終了日は必須です'
    }

    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    if (!validate()) return

    try {
      await createMarket(formData)
      // 成功時の処理
    } catch (error) {
      // エラー時の処理
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        value={formData.name}
        onChange={e => setFormData(prev => ({ ...prev, name: e.target.value }))}
        placeholder="マーケット名"
      />
      {errors.name && <span className="error">{errors.name}</span>}

      {/* その他のフィールド */}

      <button type="submit">マーケットを作成</button>
    </form>
  )
}

エラーバウンダリパターン

interface ErrorBoundaryState {
  hasError: boolean
  error: Error | null
}

export class ErrorBoundary extends React.Component<
  { children: React.ReactNode },
  ErrorBoundaryState
> {
  state: ErrorBoundaryState = {
    hasError: false,
    error: null
  }

  static getDerivedStateFromError(error: Error): ErrorBoundaryState {
    return { hasError: true, error }
  }

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    console.error('Error boundary caught:', error, errorInfo)
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="error-fallback">
          <h2>何か問題が発生しました</h2>
          <p>{this.state.error?.message}</p>
          <button onClick={() => this.setState({ hasError: false })}>
            再試行
          </button>
        </div>
      )
    }

    return this.props.children
  }
}

// 使用例
<ErrorBoundary>
  <App />
</ErrorBoundary>

アニメーションパターン

Framer Motion アニメーション

import { motion, AnimatePresence } from 'framer-motion'

// PASS: リストアニメーション
export function AnimatedMarketList({ markets }: { markets: Market[] }) {
  return (
    <AnimatePresence>
      {markets.map(market => (
        <motion.div
          key={market.id}
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          exit={{ opacity: 0, y: -20 }}
          transition={{ duration: 0.3 }}
        >
          <MarketCard market={market} />
        </motion.div>
      ))}
    </AnimatePresence>
  )
}

// PASS: モーダルアニメーション
export function Modal({ isOpen, onClose, children }: ModalProps) {
  return (
    <AnimatePresence>
      {isOpen && (
        <>
          <motion.div
            className="modal-overlay"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            onClick={onClose}
          />
          <motion.div
            className="modal-content"
            initial={{ opacity: 0, scale: 0.9, y: 20 }}
            animate={{ opacity: 1, scale: 1, y: 0 }}
            exit={{ opacity: 0, scale: 0.9, y: 20 }}
          >
            {children}
          </motion.div>
        </>
      )}
    </AnimatePresence>
  )
}

アクセシビリティパターン

キーボードナビゲーション

export function Dropdown({ options, onSelect }: DropdownProps) {
  const [isOpen, setIsOpen] = useState(false)
  const [activeIndex, setActiveIndex] = useState(0)

  const handleKeyDown = (e: React.KeyboardEvent) => {
    switch (e.key) {
      case 'ArrowDown':
        e.preventDefault()
        setActiveIndex(i => Math.min(i + 1, options.length - 1))
        break
      case 'ArrowUp':
        e.preventDefault()
        setActiveIndex(i => Math.max(i - 1, 0))
        break
      case 'Enter':
        e.preventDefault()
        onSelect(options[activeIndex])
        break
      case 'Escape':
        e.preventDefault()
        setIsOpen(false)
        break
    }
  }

  return (
    <div onKeyDown={handleKeyDown}>
      <button onClick={() => setIsOpen(!isOpen)}>
        選択
      </button>
      {isOpen && (
        <ul role="listbox">
          {options.map((option, index) => (
            <li
              key={option.value}
              role="option"
              aria-selected={index === activeIndex}
              className={index === activeIndex ? 'active' : ''}
              onClick={() => onSelect(option)}
            >
              {option.label}
            </li>
          ))}
        </ul>
      )}
    </div>
  )
}

ARIA属性とセマンティックHTML

// PASS: 適切なARIAラベルとロールを使用
export function SearchInput({ value, onChange }: SearchInputProps) {
  return (
    <div role="search">
      <label htmlFor="market-search" className="sr-only">
        マーケットを検索
      </label>
      <input
        id="market-search"
        type="search"
        value={value}
        onChange={e => onChange(e.target.value)}
        aria-describedby="search-hint"
      />
      <p id="search-hint" className="sr-only">
        名前または説明でマーケットを検索
      </p>
    </div>
  )
}

Next.jsパターン

サーバーコンポーネントとクライアントコンポーネント

// app/markets/page.tsx - デフォルトでサーバーコンポーネント
import { Suspense } from 'react'
import { MarketList } from './MarketList'

async function getMarkets(): Promise<Market[]> {
  const res = await fetch('https://api.example.com/markets')
  return res.json()
}

export default async function MarketsPage() {
  const markets = await getMarkets()

  return (
    <div>
      <h1>マーケット一覧</h1>
      <Suspense fallback={<div>読み込み中...</div>}>
        <MarketList markets={markets} />
      </Suspense>
    </div>
  )
}

// app/markets/MarketList.tsx - 'use client' でクライアントコンポーネント
'use client'

export function MarketList({ markets }: { markets: Market[] }) {
  const [filter, setFilter] = useState('')

  const filtered = markets.filter(m =>
    m.name.toLowerCase().includes(filter.toLowerCase())
  )

  return (
    <div>
      <input
        type="text"
        placeholder="フィルター..."
        value={filter}
        onChange={e => setFilter(e.target.value)}
      />
      {filtered.map(market => (
        <div key={market.id}>{market.name}</div>
      ))}
    </div>
  )
}

テストパターン

React Testing Library

import { render, screen, fireEvent } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MarketCard } from './MarketCard'

describe('MarketCard', () => {
  const mockMarket: Market = {
    id: '1',
    name: 'テストマーケット',
    description: 'マーケットの説明',
    volume: 1000000
  }

  it('マーケット情報を表示する', () => {
    render(<MarketCard market={mockMarket} />)

    expect(screen.getByText('テストマーケット')).toBeInTheDocument()
    expect(screen.getByText('マーケットの説明')).toBeInTheDocument()
  })

  it('クリックハンドラが呼び出される', async () => {
    const onClick = jest.fn()
    render(<MarketCard market={mockMarket} onClick={onClick} />)

    await userEvent.click(screen.getByRole('button'))

    expect(onClick).toHaveBeenCalledTimes(1)
    expect(onClick).toHaveBeenCalledWith(mockMarket)
  })
})

ベストプラクティスのまとめ

Reactコンポーネント

  1. パフォーマンスの前に構成: まずコンポーネントを適切に構成する。パフォーマンスの問題が発生した場合にのみ最適化する。
  2. カスタムフックを使用: ロジックをカスタムフックに抽出して再利用性を高める。
  3. 型安全: すべてのプロパティと状態にTypeScriptを使用する。
  4. 不変性を保つ: 状態を直接変更せず、常に新しいオブジェクト/配列を作成する。
  5. アクセシビリティ: キーボードナビゲーションとスクリーンリーダーのサポートを含める。

Next.js固有

  1. 可能な限りサーバーコンポーネントを優先: デフォルトではサーバーコンポーネントを使用し、必要な場合のみ'use client'を追加する。
  2. データフェッチ: サーバーコンポーネントで直接フェッチするか、クライアントではSWR/React Queryを使用する。
  3. 画像最適化: 組み込みのnext/imageコンポーネントを使用する。
  4. ルーティング: 型安全なルーティングのためにApp RouterとLinkコンポーネントを使用する。
  5. メタデータ: generateMetadataを使用した動的メタデータを利用する。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

関連スキル