--- name: react-patterns description: Implement React patterns with TypeScript including custom hooks, composition, container/presenter, error boundaries, and forms with validation. Use when you need to create React components, structure features, build forms, or solve frontend architecture problems. version: 1.0.0 author: Maestro --- # React Patterns Apply proven React + TypeScript patterns for scalable, maintainable frontend code. ## When to Use - User needs to create a custom hook for data fetching or shared logic - User wants to structure a feature using container/presenter pattern - User needs to build a form with validation (React Hook Form + Zod) - User wants to add error boundaries to catch rendering errors - User needs to compose components instead of using deep prop drilling ## Available Operations 1. Create custom hooks for data fetching with React Query 2. Build components using composition pattern (slots, children) 3. Implement container/presenter separation 4. Add error boundaries with recovery 5. Build validated forms with React Hook Form + Zod ## Multi-Step Workflow ### Step 1: Set Up Project Dependencies ```bash npm install @tanstack/react-query react-hook-form @hookform/resolvers zod react-error-boundary npm install -D @types/react @types/react-dom typescript ``` ### Step 2: Create Custom Hooks for Data Fetching ```tsx // src/hooks/useItems.ts import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; import { itemApi } from '../services/itemApi'; import { toast } from 'sonner'; export function useItems(filters?: ItemFilters) { return useQuery({ queryKey: ['items', filters], queryFn: () => itemApi.list(filters), staleTime: 30_000, }); } export function useItem(id: string) { return useQuery({ queryKey: ['items', id], queryFn: () => itemApi.get(id), enabled: !!id, }); } export function useCreateItem() { const queryClient = useQueryClient(); return useMutation({ mutationFn: itemApi.create, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['items'] }); toast.success('Item created'); }, onError: (err) => toast.error(err.message), }); } ``` ### Step 3: Build Components with Composition ```tsx // src/components/Card.tsx interface CardProps { children: React.ReactNode; className?: string; } export function Card({ children, className }: CardProps) { return
{children}
; } Card.Header = function CardHeader({ children }: { children: React.ReactNode }) { return
{children}
; }; Card.Content = function CardContent({ children }: { children: React.ReactNode }) { return
{children}
; }; Card.Footer = function CardFooter({ children }: { children: React.ReactNode }) { return
{children}
; }; // Usage:

{item.title}

{item.description}

``` ### Step 4: Implement Container/Presenter Pattern ```tsx // Container: owns data fetching and state function ItemListContainer() { const { data, isLoading, error } = useItems(); const [selected, setSelected] = useState(null); if (isLoading) return ; if (error) return ; return ; } // Presenter: pure rendering, easy to test interface ItemListProps { items: Item[]; selected: string | null; onSelect: (id: string) => void; } function ItemList({ items, selected, onSelect }: ItemListProps) { return (
{items.map((item) => ( onSelect(item.id)} /> ))}
); } ``` ### Step 5: Add Error Boundaries ```tsx // src/components/AppErrorBoundary.tsx import { ErrorBoundary } from 'react-error-boundary'; function ErrorFallback({ error, resetErrorBoundary }: { error: Error; resetErrorBoundary: () => void }) { return (

Something went wrong

{error.message}

); } export function AppErrorBoundary({ children }: { children: React.ReactNode }) { return {children}; } ``` ### Step 6: Build Validated Forms ```tsx // src/features/items/CreateItemForm.tsx import { useForm } from 'react-hook-form'; import { zodResolver } from '@hookform/resolvers/zod'; import { z } from 'zod'; const itemSchema = z.object({ title: z.string().min(3, 'Title must be at least 3 characters'), description: z.string().min(10, 'Description must be at least 10 characters'), priority: z.enum(['low', 'medium', 'high']), }); type ItemFormData = z.infer; export function CreateItemForm() { const { register, handleSubmit, formState: { errors } } = useForm({ resolver: zodResolver(itemSchema), }); const createItem = useCreateItem(); return (
createItem.mutate(data))}>
{errors.title &&

{errors.title.message}

}