React Development Patterns
Ta treść nie jest jeszcze dostępna w Twoim języku.
Master React development with AI assistance using proven patterns and workflows for Cursor IDE and Claude Code. These recipes cover everything from component creation to state management, testing, and performance optimization.
Quick Setup for React Projects
Section titled “Quick Setup for React Projects”Initialize React Project with AI Assistance
Section titled “Initialize React Project with AI Assistance”- Open Cursor and create a new project
- Open Agent mode (Cmd/Ctrl + I)
- Prompt: “Use Context7 to get the latest Vite documentation. Create a new React TypeScript project with Vite, Tailwind CSS, and testing setup using current best practices”
- Enable YOLO mode to let Cursor run all setup commands automatically
- Review the generated project structure and configuration files
- Navigate to your projects directory
- Run
claude
to start Claude Code - Enable Figma MCP if using designs:
claude mcp add figma --transport sse http://127.0.0.1:3845/sse
- Use: “Use Context7 to get latest Vite and Vitest documentation. Create a new React TypeScript project with Vite, Tailwind CSS, vitest for testing, and proper folder structure following current best practices”
- Claude will execute all necessary commands and create the project structure
- Run
/init
to create a CLAUDE.md file with React-specific guidelines
Configure AI Context for React
Section titled “Configure AI Context for React”Figma Integration Setup
Section titled “Figma Integration Setup”{ "mcpServers": { "figma": { "type": "sse", "url": "http://127.0.0.1:3845/sse" } }}
Create context files to help AI understand your React patterns:
# React Development Rules
## Component Standards- Use functional components with TypeScript- Prefer named exports for components- Keep components under 150 lines- Extract custom hooks for logic reuse
## State Management- Use React Query/TanStack Query for server state- Zustand for client-side global state- Local state with useState for component-specific data
## Testing Requirements- Write tests for all components using vitest and @testing-library/react- Minimum 80% coverage for business logic- Test user interactions, not implementation details
Component Development Patterns
Section titled “Component Development Patterns”Creating New Components
Section titled “Creating New Components”Scenario: Convert a Figma design to a React component
Using Figma MCP Server:
# Enable Figma MCP in your Figma desktop app# Preferences > Enable Dev Mode MCP Server
# Add Figma MCP to Claude Codeclaude mcp add figma --transport sse http://127.0.0.1:3845/sse
# Or add to Cursor# Settings > MCP > Add Server > URL: http://127.0.0.1:3845/sse
Cursor Workflow with Figma MCP:
- Select the component in Figma (with MCP server running)
- In Cursor: “Using the Figma MCP server, generate a React component from my current Figma selection. Use TypeScript and Tailwind CSS”
- The AI will use
get_code
to fetch the exact design structure - Review generated component with proper design tokens
Alternative Manual Workflow:
- Take a screenshot of the Figma design
- Drag the image into Cursor chat
- Prompt: “Create a React component based on this design. Use TypeScript, Tailwind CSS for styling, and make it responsive”
- Review the generated component
- Ask: “Add proper TypeScript types and make the component reusable with props”
Claude Code Workflow:
- Save the design screenshot in your project
- Reference it: “Look at design.png and create a React component that matches this design. Use TypeScript, Tailwind CSS, and ensure it’s fully responsive”
- Claude will analyze the image and generate the component
- Follow up: “Add Storybook stories for this component with different states”
Scenario: Build a data table component with sorting and filtering
Example Prompt:
Create a reusable DataTable component with these features:- TypeScript with proper generics for row data type- Column sorting (click header to sort)- Text filtering for each column- Pagination with customizable page size- Loading and empty states- Use Tailwind CSS for styling- Make it accessible with proper ARIA labels
Enhancement Workflow:
- Generate the base component
- Extract design tokens: “Using Figma MCP, get all design variables (colors, spacing, typography) used in this component”
- Add features incrementally: “Add row selection with checkbox column”
- Optimize: “Add virtualization for large datasets using @tanstack/react-virtual”
- Test: “Write comprehensive tests for sorting and filtering logic”
Refactoring Class Components to Hooks
Section titled “Refactoring Class Components to Hooks”Cursor Agent Mode Approach:
I have a class component in UserProfile.tsx that needs to be converted to a functional component with hooks.Please:1. Convert all lifecycle methods to useEffect2. Convert state to useState3. Extract any complex logic into custom hooks4. Maintain all existing functionality5. Update the tests to work with the new implementation
State Management Recipes
Section titled “State Management Recipes”Setting Up Zustand Store
Section titled “Setting Up Zustand Store”# First get the latest Zustand patternsUse Context7 to fetch Zustand documentation and best practices
# Then create the store following current patternsCreate a Zustand store for managing user authentication with:- User profile data- Login/logout actions- Persist to localStorage- TypeScript types for all state and actions- Selectors for commonly accessed data- DevTools integration
React Query Integration
Section titled “React Query Integration”Claude Code Recipe:
# First, get the latest React Query documentationUse Context7 to get TanStack Query documentation for v5
# Then implement based on current best practicesSet up React Query in our app with:1. Configure QueryClient with sensible defaults2. Create custom hooks for our API endpoints3. Add optimistic updates for mutations4. Implement proper error handling5. Set up query invalidation patterns
Design System Integration
Section titled “Design System Integration”Using Figma Code Connect
Section titled “Using Figma Code Connect”# PRD: Integrate Figma design system with React codebase# Plan: Use Figma Code Connect for component mapping
"Using Figma MCP with Code Connect enabled:1. Get code connect mappings for design system components2. Generate React components that use our existing component library3. Extract and apply design tokens consistently"
# Example workflow"Select the Button component in Figma and generate React code that:- Uses our existing Button component from '@/components/ui'- Applies the correct variant based on Figma properties- Uses our design token system for colors and spacing"
Extracting Design Tokens
Section titled “Extracting Design Tokens”// Use Figma MCP to extract design tokens"Using Figma MCP get_variable_defs:1. List all color tokens used in the selected design2. List spacing and typography tokens3. Generate a theme configuration file"
// Example outputexport const theme = { colors: { primary: { blue: '#1D4ED8', // From Figma: Primary/Blue dark: '#1E40AF' // From Figma: Primary/Dark }, neutral: { gray90: '#1A1A1A' // From Figma: Neutral/Gray90 } }, spacing: { sm: '8px', // From Figma: Spacing/S md: '16px', // From Figma: Spacing/M lg: '24px' // From Figma: Spacing/L }};
Advanced Patterns
Section titled “Advanced Patterns”Performance Optimization
Section titled “Performance Optimization”-
Identify Performance Issues
- Cursor: “Analyze MyComponent.tsx for potential performance issues and suggest optimizations”
- Claude Code: “Review the entire components directory and identify components that could benefit from React.memo, useMemo, or useCallback”
-
Implement Optimizations
Optimize the ProductList component:- Add React.memo with proper comparison function- Use useMemo for expensive calculations- Implement virtualization for the list- Add lazy loading for images -
Verify Improvements
- Generate performance tests
- Add React DevTools Profiler markers
- Create benchmarks for critical paths
- Use Context7 to get latest React performance optimization patterns
Custom Hooks Library
Section titled “Custom Hooks Library”Building a Custom Hooks Collection:
- Create a new file:
src/hooks/index.ts
- Agent prompt: “Create a collection of useful custom hooks for our React app including useDebounce, useLocalStorage, useFetch, useIntersectionObserver, and useMediaQuery. Include TypeScript types and JSDoc comments”
- For each hook, ask: “Add comprehensive tests for useDebounce hook”
- Use planning mode:
/think Create a well-organized custom hooks library
- Execute: “Create custom hooks in separate files under src/hooks/ with proper exports, TypeScript types, tests, and documentation”
- Generate usage examples: “Create a hooks showcase page demonstrating each custom hook”
Testing Patterns
Section titled “Testing Patterns”Component Testing Strategy
Section titled “Component Testing Strategy”// Cursor/Claude Code Prompt:Write comprehensive tests for the UserDashboard component:1. Test loading states2. Test error states3. Test successful data rendering4. Test user interactions (clicks, form submissions)5. Test accessibility requirements6. Mock API calls properly7. Use @testing-library/react best practices
Integration Testing
Section titled “Integration Testing”Multi-Component Interaction Testing:
Create integration tests for the checkout flow:- Test the entire flow from cart to payment- Mock API responses for different scenarios- Test error recovery- Verify proper state updates across components- Test loading states between steps
React Native Patterns
Section titled “React Native Patterns”Cross-Platform Component Development
Section titled “Cross-Platform Component Development”Shared Component Library:
# PRD: Need cross-platform button component# Plan: Use Context7 to research React Native Web patterns# Todo:1. Use Context7 to get React Native documentation for cross-platform components2. Create a Button component that works in both React web and React Native: - [ ] Use a shared types file - [ ] Create platform-specific implementations - [ ] Export from a common index file - [ ] Include proper styling for each platform - [ ] Add Storybook stories for web - [ ] Add examples for React Native
Common Pitfalls and Solutions
Section titled “Common Pitfalls and Solutions”Avoiding Over-Rendering
Section titled “Avoiding Over-Rendering”Diagnosis and Fix Pattern:
- Identify: “Find components in our app that might be re-rendering unnecessarily”
- Analyze: “Add console.logs or React DevTools Profiler integration to track renders”
- Fix: “Implement proper memoization and state lifting where needed”
- Verify: “Create tests to ensure render count stays optimal”
Managing Side Effects
Section titled “Managing Side Effects”useEffect Best Practices:
Review all useEffect hooks in the components/ directory and:1. Ensure proper dependency arrays2. Add cleanup functions where needed3. Identify effects that should be event handlers instead4. Split complex effects into smaller, focused ones5. Add comments explaining why each effect is necessary
Deployment and Build Optimization
Section titled “Deployment and Build Optimization”Production Build Configuration
Section titled “Production Build Configuration”Optimization Checklist:
Prepare our React app for production:1. Configure code splitting with React.lazy2. Set up proper tree shaking3. Optimize bundle size with dynamic imports4. Configure proper caching headers5. Set up error boundaries6. Add performance monitoring7. Create a bundle analysis script
Next Steps
Section titled “Next Steps”- Explore Vue.js Patterns for alternative framework approaches
- Check out Next.js Patterns for full-stack React applications
- Learn about Testing Patterns for comprehensive quality assurance