Communitygithub.com

ComeOnOliver/skillshub

Modèles de développement frontend pour React, Next.js, gestion d'état, optimisation des performances et bonnes pratiques d'interface utilisateur.

Qu'est-ce que skillshub ?

Cette compétence fournit un ensemble complet de modèles et de bonnes pratiques pour le développement frontend moderne, en se concentrant sur React, Next.js et la création d'interfaces utilisateur performantes. Elle couvre les modèles de composants (composition, composants composés, render props), les hooks personnalisés (gestion d'état, récupération de données asynchrones, debounce), les stratégies de gestion d'état (Context + Reducer), et l'optimisation des performances (mémoïsation, séparation de code, virtualisation). La compétence inclut également des modèles pour la gestion des formulaires, les limites d'erreur, les animations avec Framer Motion, et l'accessibilité (navigation clavier, gestion du focus). Elle est conçue pour les développeurs utilisant des agents IA comme Claude Code, Cursor ou Codex, et offre des exemples de code TypeScript prêts à l'emploi dans les fichiers SKILL.md. Les modèles sont organisés par catégories avec des extraits de code clairs et des explications, facilitant leur intégration directe dans des projets de développement frontend.

Compatible avec~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/aiskillstore/marketplace/sickn33/cc-skill-frontend-patterns

Demander à votre IA préférée

Ouvre une nouvelle conversation avec cette compétence d'agent déjà préchargée.

Documentation

Modèles de Développement Frontend

Modèles frontend modernes pour React, Next.js et des interfaces utilisateur performantes.

Modèles de Composants

Composition plutôt qu'Héritage

// ✅ BON : Composition de composants
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>
}

// Utilisation
<Card>
  <CardHeader>Titre</CardHeader>
  <CardBody>Contenu</CardBody>
</Card>

Composants Composés

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 doit être utilisé dans Tabs')

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

// Utilisation
<Tabs defaultTab="apercu">
  <TabList>
    <Tab id="apercu">Aperçu</Tab>
    <Tab id="details">Détails</Tab>
  </TabList>
</Tabs>

Modèle Render Props

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)}</>
}

// Utilisation
<DataLoader<Marché[]> url="/api/marches">
  {(marches, loading, error) => {
    if (loading) return <Spinner />
    if (error) return <Erreur error={error} />
    return <ListeMarches marches={marches!} />
  }}
</DataLoader>

Modèles de Hooks Personnalisés

Hook de Gestion d'État

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

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

  return [value, toggle]
}

// Utilisation
const [isOpen, toggleOpen] = useToggle()

Hook de Récupération de Données asynchrones

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)

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

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

  useEffect(() => {
    if (options?.enabled !== false) {
      refetch()
    }
  }, [key, refetch, options?.enabled])

  return { data, error, loading, refetch }
}

// Utilisation
const { data: marches, loading, error, refetch } = useQuery(
  'marches',
  () => fetch('/api/marches').then(r => r.json()),
  {
    onSuccess: data => console.log('Récupéré', data.length, 'marchés'),
    onError: err => console.error('Échec :', err)
  }
)

Hook Debounce

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
}

// Utilisation
const [searchQuery, setSearchQuery] = useState('')
const debouncedQuery = useDebounce(searchQuery, 500)

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

Modèles de Gestion d'État

Modèle Contexte + Réducteur

interface State {
  marches: Marché[]
  selectedMarket: Marché | null
  loading: boolean
}

type Action =
  | { type: 'SET_MARCHES'; payload: Marché[] }
  | { type: 'SELECT_MARCHE'; payload: Marché }
  | { type: 'SET_LOADING'; payload: boolean }

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case 'SET_MARCHES':
      return { ...state, marches: action.payload }
    case 'SELECT_MARCHE':
      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, {
    marches: [],
    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 doit être utilisé dans MarketProvider')
  return context
}

Optimisation des Performances

Mémoïsation

// ✅ useMemo pour les calculs coûteux
const sortedMarkets = useMemo(() => {
  return marches.sort((a, b) => b.volume - a.volume)
}, [marches])

// ✅ useCallback pour les fonctions passées aux enfants
const handleSearch = useCallback((query: string) => {
  setSearchQuery(query)
}, [])

// ✅ React.memo pour les composants purs
export const MarketCard = React.memo<MarketCardProps>(({ market }) => {
  return (
    <div className="market-card">
      <h3>{market.name}</h3>
      <p>{market.description}</p>
    </div>
  )
})

Séparation du Code et Chargement Paresseux

import { lazy, Suspense } from 'react'

// ✅ Charger paresseusement les composants lourds
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>
  )
}

Virtualisation pour les Longues Listes

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

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

  const virtualizer = useVirtualizer({
    count: markets.length,
    getScrollElement: () => parentRef.current,
    estimateSize: () => 100,  // Hauteur de ligne estimée
    overscan: 5  // Éléments supplémentaires à rendre
  })

  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>
  )
}

Modèles de Gestion des Formulaires

Formulaire Contrôlé avec Validation

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 = 'Le nom est requis'
    } else if (formData.name.length > 200) {
      newErrors.name = 'Le nom doit faire moins de 200 caractères'
    }

    if (!formData.description.trim()) {
      newErrors.description = 'La description est requise'
    }

    if (!formData.endDate) {
      newErrors.endDate = 'La date de fin est requise'
    }

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

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

    if (!validate()) return

    try {
      await createMarket(formData)
      // Gestion du succès
    } catch (error) {
      // Gestion des erreurs
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        value={formData.name}
        onChange={e => setFormData(prev => ({ ...prev, name: e.target.value }))}
        placeholder="Nom du marché"
      />
      {errors.name && <span className="error">{errors.name}</span>}

      {/* Autres champs */}

      <button type="submit">Créer le marché</button>
    </form>
  )
}

Modèle de Limite d'Erreur

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('Limite d\'erreur attrapée :', error, errorInfo)
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="error-fallback">
          <h2>Quelque chose s'est mal passé</h2>
          <p>{this.state.error?.message}</p>
          <button onClick={() => this.setState({ hasError: false })}>
            Réessayer
          </button>
        </div>
      )
    }

    return this.props.children
  }
}

// Utilisation
<ErrorBoundary>
  <App />
</ErrorBoundary>

Modèles d'Animation

Animations avec Framer Motion

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

// ✅ Animations de liste
export function AnimatedMarketList({ markets }: { markets: Marché[] }) {
  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>
  )
}

// ✅ Animations de modale
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>
  )
}

Modèles d'Accessibilité

Navigation au Clavier

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])
        setIsOpen(false)
        break
      case 'Escape':
        setIsOpen(false)
        break
    }
  }

  return (
    <div
      role="combobox"
      aria-expanded={isOpen}
      aria-haspopup="listbox"
      onKeyDown={handleKeyDown}
    >
      {/* Implémentation du menu déroulant */}
    </div>
  )
}

Gestion du Focus

export function Modal({ isOpen, onClose, children }: ModalProps) {
  const modalRef = useRef<HTMLDivElement>(null)
  const previousFocusRef = useRef<HTMLElement | null>(null)

  useEffect(() => {
    if (isOpen) {
      // Sauvegarder l'élément actuellement focus
      previousFocusRef.current = document.activeElement as HTMLElement

      // Focus la modale
      modalRef.current?.focus()
    } else {
      // Restaurer le focus lors de la fermeture
      previousFocusRef.current?.focus()
    }
  }, [isOpen])

  return isOpen ? (
    <div
      ref={modalRef}
      role="dialog"
      aria-modal="true"
      tabIndex={-1}
      onKeyDown={e => e.key === 'Escape' && onClose()}
    >
      {children}
    </div>
  ) : null
}

Meilleures Pratiques UI

Conception Réactive

// ✅ Approche mobile-first avec les classes utilitaires Tailwind
<header className="flex flex-col md:flex-row justify-between items-center p-4 gap-4">
  <h1 className="text-lg md:text-2xl font-bold">{title}</h1>
  <div className="flex gap-2 w-full md:w-auto">
    <input
      className="flex-1 md:flex-initial px-3 py-2"
      placeholder="Rechercher..."
      value={searchQuery}
      onChange={handleSearch}
    />
    <button
      className="px-4 py-2 bg-blue-500 text-white rounded"
      onClick={handleFilter}
    >
      Filtrer
    </button>
  </div>
</header>

Système de Design Cohérent

// ✅ Jetons de design en tant que variables CSS
const theme = {
  colors: {
    primary: '#3B82F6',
    secondary: '#10B981',
    background: '#F9FAFB',
    text: '#111827'
  },
  spacing: {
    xs: '0.25rem',
    sm: '0.5rem',
    md: '1rem',
    lg: '1.5rem',
    xl: '2rem'
  },
  borderRadius: {
    sm: '0.25rem',
    md: '0.5rem',
    lg: '1rem'
  }
}

// Utilisation dans les composants
<button
  style={{
    backgroundColor: theme.colors.primary,
    padding: `${theme.spacing.sm} ${theme.spacing.md}`,
    borderRadius: theme.borderRadius.md
  }}
>
  Cliquez-moi
</button>

Tests

Tests de Composants avec React Testing Library

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

// ✅ Tester le comportement, pas l'implémentation
describe('MarketCard', () => {
  it('affiche les détails du marché', () => {
    render(<MarketCard market={mockMarket} />)

    expect(screen.getByText('Marché Test')).toBeInTheDocument()
    expect(screen.getByText('Description du marché')).toBeInTheDocument()
  })

  it('gère le clic sur le bouton de suivi', async () => {
    const onFollow = jest.fn()
    render(<MarketCard market={mockMarket} onFollow={onFollow} />)

    await userEvent.click(screen.getByRole('button', { name: 'Suivre' }))

    expect(onFollow).toHaveBeenCalledWith('market-1')
  })
})

// ✅ Tester les interactions utilisateur
describe('SearchBar', () => {
  it('appelle onChange avec la requête debounced', async () => {
    const onChange = jest.fn()
    render(<SearchBar onChange={onChange} />)

    const input = screen.getByPlaceholderText('Rechercher...')
    fireEvent.change(input, { target: { value: 'test' } })

    // Attendre le debounce
    await waitFor(() => {
      expect(onChange).toHaveBeenCalledWith('test')
    })
  })
})

Tests de Hooks

import { renderHook, act } from '@testing-library/react'

// ✅ Tester les hooks personnalisés
describe('useToggle', () => {
  it('initialise avec la valeur par défaut', () => {
    const { result } = renderHook(() => useToggle())

    expect(result.current[0]).toBe(false)
  })

  it('bascule la valeur', () => {
    const { result } = renderHook(() => useToggle())

    act(() => {
      result.current[1]()
    })

    expect(result.current[0]).toBe(true)

    act(() => {
      result.current[1]()
    })

    expect(result.current[0]).toBe(false)
  })
})

Dépendances Recommandées

  • @tanstack/react-virtual – pour la virtualisation de listes
  • framer-motion – pour les animations
  • @testing-library/react – pour les tests de composants
  • @testing-library/user-event – pour simuler les interactions utilisateur
  • react-error-boundary – pour une gestion des erreurs plus flexible

Individual skills in this repo

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

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

This document captures learnings from fixing keyboard navigation issues when floating components (Select, DropdownMenu, Popover) have CSS open/close animations.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

Skills associés