Back to Basics

AI-Powered Code Generation

Master Cursor's code generation capabilities with Claude 4.5 Sonnet, Composer, and advanced AI features.

Code Generation Overview

Cursor's code generation is powered by Claude 4.5 Sonnet and understands your entire codebase context for intelligent, relevant code creation.

Smart Generation

  • • Context-aware code creation
  • • Follows project patterns
  • • Maintains code consistency
  • • Understands dependencies

Multi-file Support

  • • Generate complete features
  • • Create related files
  • • Update existing code
  • • Maintain relationships

Intelligent Patterns

  • • Learns from your codebase
  • • Suggests best practices
  • • Adapts to your style
  • • Provides explanations
1

Basic Code Generation

Start with simple code generation using natural language prompts in AI Chat.

Simple Components

Basic React Component

TEXT
Create a simple button component with:
- Click handler
- Disabled state
- Loading state
- TypeScript types
Generated Code:
TSX
interface ButtonProps {
  onClick: () => void;
  disabled?: boolean;
  loading?: boolean;
  children: React.ReactNode;
}

export const Button: React.FC<ButtonProps> = ({
  onClick,
  disabled = false,
  loading = false,
  children
}) => {
  return (
    <button
      onClick={onClick}
      disabled={disabled || loading}
      className={`px-4 py-2 rounded font-medium transition-colors ${
        disabled || loading
          ? 'bg-gray-300 text-gray-500 cursor-not-allowed'
          : 'bg-blue-600 text-white hover:bg-blue-700'
      }`}
    >
      {loading ? 'Loading...' : children}
    </button>
  );
};

Custom Hook

TEXT
Create a custom hook for managing form state with:
- Form data object
- Validation errors
- Submit handler
- Reset function
- TypeScript support
Generated Code:
TSX
interface UseFormProps<T> {
  initialValues: T;
  validate?: (values: T) => Partial<Record<keyof T, string>>;
  onSubmit: (values: T) => void | Promise<void>;
}

export const useForm = <T extends Record<string, any>>({
  initialValues,
  validate,
  onSubmit
}: UseFormProps<T>) => {
  const [values, setValues] = useState<T>(initialValues);
  const [errors, setErrors] = useState<Partial<Record<keyof T, string>>>({});
  const [isSubmitting, setIsSubmitting] = useState(false);

  const handleChange = (name: keyof T, value: any) => {
    setValues(prev => ({ ...prev, [name]: value }));
    if (errors[name]) {
      setErrors(prev => ({ ...prev, [name]: undefined }));
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (validate) {
      const validationErrors = validate(values);
      if (Object.keys(validationErrors).length > 0) {
        setErrors(validationErrors);
        return;
      }
    }

    setIsSubmitting(true);
    try {
      await onSubmit(values);
    } finally {
      setIsSubmitting(false);
    }
  };

  const reset = () => {
    setValues(initialValues);
    setErrors({});
  };

  return {
    values,
    errors,
    isSubmitting,
    handleChange,
    handleSubmit,
    reset
  };
};

API Integration

API Client

TEXT
Create an API client for user management with:
- GET /users endpoint
- POST /users endpoint
- PUT /users/:id endpoint
- DELETE /users/:id endpoint
- Error handling
- TypeScript types

React Query Hook

TEXT
Create a React Query hook for fetching users with:
- useQuery for GET
- useMutation for POST/PUT/DELETE
- Optimistic updates
- Error handling
- Loading states

Generation Best Practices

Be Specific

Include details about props, types, styling, and behavior.

Mention Your Stack

Specify React, TypeScript, styling library, etc.

Include Requirements

Mention accessibility, performance, or specific patterns.

2

Advanced Code Generation

Use Composer for complex, multi-file code generation that understands your entire project.

Complete Feature Development

User Authentication System

TEXT
Create a complete authentication system with:

Files to create:
- components/auth/LoginForm.tsx
- components/auth/RegisterForm.tsx
- components/auth/ProtectedRoute.tsx
- context/AuthContext.tsx
- hooks/useAuth.ts
- types/auth.ts
- utils/auth.ts
- services/authService.ts

Features:
- Email/password login
- User registration
- JWT token handling
- Protected routes
- Form validation
- Error handling
- Loading states
- TypeScript types
- Responsive design

Composer will create all files with proper imports, types, and consistent code style.

Dashboard with Data Visualization

TEXT
Create a dashboard with:

Components:
- DashboardLayout.tsx
- StatsCard.tsx
- Chart.tsx
- DataTable.tsx
- FilterBar.tsx

Features:
- Real-time data fetching
- Interactive charts
- Data filtering
- Export functionality
- Responsive design
- Loading states
- Error handling

Code Refactoring

Component Refactoring

TEXT
Refactor this large component into smaller, reusable components:

Current: UserProfile.tsx (500+ lines)
Break it down into:
- UserProfileHeader.tsx
- UserProfileDetails.tsx
- UserProfileActions.tsx
- UserProfileSettings.tsx
- hooks/useUserProfile.ts
- types/userProfile.ts

Maintain all existing functionality and improve code organization.

State Management Migration

TEXT
Migrate from useState to Redux Toolkit:

Current: Multiple components using useState for user data
Create:
- store/userSlice.ts
- store/index.ts
- hooks/useAppDispatch.ts
- hooks/useAppSelector.ts

Update all components to use Redux while maintaining functionality.

Design Pattern Implementation

Observer Pattern

TEXT
Implement the Observer pattern for a notification system:

Create:
- types/observer.ts
- utils/NotificationSubject.ts
- hooks/useNotification.ts
- components/NotificationCenter.tsx

Features:
- Subscribe/unsubscribe to notifications
- Multiple notification types
- Priority handling
- Auto-dismiss functionality

Factory Pattern

TEXT
Create a factory for different chart types:

Create:
- types/chart.ts
- factories/ChartFactory.ts
- components/charts/LineChart.tsx
- components/charts/BarChart.tsx
- components/charts/PieChart.tsx
- components/ChartRenderer.tsx

Features:
- Dynamic chart creation
- Consistent interface
- Easy to extend
- TypeScript support
3

Context-Aware Generation

Leverage Cursor's understanding of your codebase for intelligent, context-aware code generation.

Using @-mentions for Context

File-Specific Generation

TEXT
@components/Button.tsx Create a loading variant of this button that matches the existing design system

AI will analyze the existing Button component and create a loading variant that matches its style.

Function Extension

TEXT
@utils/formatDate Add support for relative time formatting (e.g., "2 hours ago") to this function

AI will understand the current function and extend it with new functionality.

Multiple File Context

TEXT
@components/UserCard.tsx @components/UserList.tsx Create a UserGrid component that combines the layout of UserList with the design of UserCard

AI will analyze both components and create a new one that combines their best features.

Project Pattern Recognition

Following Existing Patterns

TEXT
Create a new API endpoint that follows the same patterns as the existing user endpoints in this project

AI will analyze your existing API patterns and create consistent code.

Style Consistency

TEXT
Create a new form component that matches the styling and validation patterns used in the existing forms

AI will understand your form patterns and create consistent styling and validation.

Architecture Consistency

TEXT
Add a new feature to the dashboard that follows the same architecture as the existing features

AI will understand your project architecture and create code that fits seamlessly.

Dependency-Aware Generation

Import Management

TEXT
Create a new utility function that uses the existing date formatting utilities and follows the same import patterns

AI will automatically include the correct imports and follow your project's import conventions.

Type Integration

TEXT
Create a new API service that uses the existing User type and follows the same error handling patterns

AI will use your existing types and maintain consistency with your error handling approach.

4

Code Quality and Testing

Generate high-quality code with proper testing, documentation, and error handling.

Test Generation

Unit Tests

TEXT
Create comprehensive unit tests for the UserProfile component including:
- Rendering tests
- User interaction tests
- Error state tests
- Loading state tests
- Accessibility tests

Integration Tests

TEXT
Create integration tests for the authentication flow including:
- Login success/failure scenarios
- Token handling
- Protected route access
- Logout functionality

Documentation Generation

JSDoc Comments

TEXT
Add comprehensive JSDoc comments to the useAuth hook including:
- Description of the hook
- Parameter documentation
- Return value documentation
- Usage examples
- Error handling notes

README Updates

TEXT
Update the README.md to include documentation for the new authentication system including:
- Installation instructions
- Usage examples
- API reference
- Configuration options

Error Handling

Robust Error Handling

TEXT
Add comprehensive error handling to the API client including:
- Network error handling
- HTTP status code handling
- Retry logic for failed requests
- User-friendly error messages
- Logging for debugging

Error Boundaries

TEXT
Create error boundaries for the React application including:
- Global error boundary
- Feature-specific error boundaries
- Error reporting
- Fallback UI components
- Recovery mechanisms

Next Steps

Now that you understand code generation, explore advanced Cursor features and settings: