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 listesframer-motion– pour les animations@testing-library/react– pour les tests de composants@testing-library/user-event– pour simuler les interactions utilisateurreact-error-boundary– pour une gestion des erreurs plus flexible