# React Frontend Development Rules

## Overview

This project uses React for building modern, interactive user interfaces with a focus on component-based architecture and functional programming.

## Technology Stack

- **Framework**: React 18+
- **Language**: TypeScript/JavaScript
- **State Management**: Context API / Redux Toolkit / Zustand
- **Styling**: CSS Modules / Styled Components / Tailwind CSS
- **Testing**: Jest, React Testing Library
- **Build Tool**: Vite / Create React App
- **Router**: React Router

## Code Style & Best Practices

### File Structure

```
src/
├── components/
│   ├── common/
│   │   ├── Button/
│   │   │   ├── Button.tsx
│   │   │   ├── Button.module.css
│   │   │   └── index.ts
│   │   └── Modal/
│   └── features/
│       ├── auth/
│       └── dashboard/
├── hooks/
├── services/
├── utils/
├── types/
├── constants/
└── App.tsx
```

### Component Structure

- Use functional components with hooks
- Prefer TypeScript for type safety
- Use PascalCase for component names
- Keep components small and focused
- Use composition over inheritance

### Hooks

- Use built-in hooks (useState, useEffect, etc.)
- Create custom hooks for reusable logic
- Follow hooks rules (only call at top level)
- Use dependency arrays correctly in useEffect

### State Management

- Use local state for component-specific data
- Use Context API for app-wide state
- Consider Redux Toolkit for complex state
- Keep state minimal and normalized

### Styling

- Use consistent naming conventions
- Prefer CSS Modules or styled-components
- Use design tokens for consistent theming
- Make components responsive
- Follow accessibility guidelines

## Example Code Patterns

### Functional Component

```typescript
interface ButtonProps {
  variant?: 'primary' | 'secondary';
  size?: 'sm' | 'md' | 'lg';
  disabled?: boolean;
  onClick?: () => void;
  children: React.ReactNode;
}

const Button: React.FC<ButtonProps> = ({
  variant = 'primary',
  size = 'md',
  disabled = false,
  onClick,
  children,
}) => {
  return (
    <button
      className={`btn btn--${variant} btn--${size}`}
      disabled={disabled}
      onClick={onClick}
    >
      {children}
    </button>
  );
};

export default Button;
```

### Custom Hook

```typescript
import { useState, useEffect } from 'react';

interface UseApiResult<T> {
  data: T | null;
  loading: boolean;
  error: string | null;
}

function useApi<T>(url: string): UseApiResult<T> {
  const [data, setData] = useState<T | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        const response = await fetch(url);
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        const result = await response.json();
        setData(result);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'An error occurred');
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [url]);

  return { data, loading, error };
}

export default useApi;
```

### Context Example

```typescript
import React, { createContext, useContext, useReducer } from 'react';

interface AuthState {
  user: User | null;
  isAuthenticated: boolean;
}

interface AuthContextType extends AuthState {
  login: (email: string, password: string) => Promise<void>;
  logout: () => void;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

const authReducer = (state: AuthState, action: any): AuthState => {
  switch (action.type) {
    case 'LOGIN':
      return { user: action.payload, isAuthenticated: true };
    case 'LOGOUT':
      return { user: null, isAuthenticated: false };
    default:
      return state;
  }
};

export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
  children,
}) => {
  const [state, dispatch] = useReducer(authReducer, {
    user: null,
    isAuthenticated: false,
  });

  const login = async (email: string, password: string) => {
    // Login logic
    const user = await authService.login(email, password);
    dispatch({ type: 'LOGIN', payload: user });
  };

  const logout = () => {
    authService.logout();
    dispatch({ type: 'LOGOUT' });
  };

  return (
    <AuthContext.Provider value={{ ...state, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
};

export const useAuth = () => {
  const context = useContext(AuthContext);
  if (!context) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};
```

## Dependencies to Consider

- `react` - Core React library
- `react-dom` - DOM rendering
- `react-router-dom` - Client-side routing
- `@types/react` - TypeScript types
- `@types/react-dom` - TypeScript types for DOM
- `axios` - HTTP client
- `react-query` - Data fetching and caching
- `formik` or `react-hook-form` - Form handling
- `yup` - Schema validation
- `classnames` - Conditional CSS classes

## Testing

- Use React Testing Library for component testing
- Test user interactions, not implementation details
- Mock external dependencies
- Test accessibility
- Use MSW (Mock Service Worker) for API mocking

## Performance

- Use React.memo for preventing unnecessary re-renders
- Implement lazy loading with React.lazy
- Use useMemo and useCallback judiciously
- Optimize bundle size with code splitting
- Use React DevTools for profiling

## Accessibility

- Use semantic HTML elements
- Provide alt text for images
- Ensure keyboard navigation works
- Use ARIA attributes when necessary
- Test with screen readers
- Maintain proper color contrast

## Security

- Sanitize user inputs
- Use HTTPS for all API calls
- Implement proper authentication
- Validate data on both client and server
- Use Content Security Policy (CSP)
- Avoid storing sensitive data in localStorage

## Error Handling

- Use Error Boundaries for catching React errors
- Implement proper error states in components
- Log errors appropriately
- Show user-friendly error messages
- Provide fallback UI for errors

## Code Quality

- Use ESLint and Prettier
- Follow consistent naming conventions
- Write meaningful comments
- Use TypeScript for type safety
- Implement proper prop validation
- Keep functions and components small

## Build and Deployment

- Use environment variables for configuration
- Implement proper build optimization
- Use service workers for offline functionality
- Implement proper error monitoring
- Use CI/CD for automated deployments
