From 5cbc31aee9d4cd1daee9c8f5c671848dbc3c34a2 Mon Sep 17 00:00:00 2001 From: sanjeed5 Date: Wed, 17 Dec 2025 21:12:15 +0530 Subject: [PATCH] Update generation system with modern prompts and Gemini 2.5 Flash - Upgrade to gemini-2.5-flash model for better output quality - Add date context to prompts (December 2025) for current best practices - Implement Exa cache system to avoid redundant API calls - Add --refresh-exa flag to bypass cache when needed - Restructure prompts with date at end for Gemini prompt caching - Enhance system prompt to emphasize modern patterns - Switch from JSON mode to direct MDC format generation - Add loguru dependency for better logging - Remove requirements.txt in favor of uv --- pyproject.toml | 7 + requirements.txt | 5 - rules-mdc/axios.mdc | 324 ++-- rules-mdc/react.mdc | 382 ++-- rules-mdc/zustand.mdc | 906 +++------ src/config.yaml | 2 +- src/generate_mdc_files.py | 442 +++-- uv.lock | 3718 +++++++++++++++++++------------------ 8 files changed, 2818 insertions(+), 2968 deletions(-) delete mode 100644 requirements.txt diff --git a/pyproject.toml b/pyproject.toml index 7954924..547ad8c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -18,6 +18,7 @@ dependencies = [ "pyyaml>=6.0.0", "build>=1.2.2.post1", "twine>=6.1.0", + "loguru>=0.7.3", ] [build-system] @@ -26,3 +27,9 @@ build-backend = "hatchling.build" [tool.hatch.build.targets.wheel] packages = ["src"] + +[dependency-groups] +dev = [ + "pytest>=8.3.5", + "pytest-mock>=3.14.0", +] diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index 8e1a293..0000000 --- a/requirements.txt +++ /dev/null @@ -1,5 +0,0 @@ -litellm>=1.30.3 -python-dotenv>=1.0.1 -tenacity>=8.2.3 -ratelimit>=2.2.1 -pydantic>=2.6.1 \ No newline at end of file diff --git a/rules-mdc/axios.mdc b/rules-mdc/axios.mdc index 1e6dfdc..afe31f5 100644 --- a/rules-mdc/axios.mdc +++ b/rules-mdc/axios.mdc @@ -1,185 +1,227 @@ --- -description: This rule provides comprehensive guidelines for using Axios effectively, covering best practices, security considerations, and performance optimization. It aims to improve code quality, maintainability, and overall application resilience when working with Axios. -globs: *.js,*.jsx,*.ts,*.tsx +description: Comprehensive best practices for using the Axios HTTP client library, covering code organization, common patterns, performance, pitfalls, and testing. +globs: **/*.{js,jsx,ts,tsx} --- -- **Avoid hardcoding URLs**: Store API endpoints in configuration files or environment variables to enhance maintainability and avoid redundancy. -- **Centralize API Logic**: Create dedicated modules or services to encapsulate Axios instances and request logic. This promotes reusability and simplifies debugging. -- **Handle Errors Gracefully**: Implement comprehensive error handling using try-catch blocks, response interceptors, and centralized error logging. Display user-friendly error messages. -- **Use Asynchronous Functions**: Leverage `async/await` or Promises for cleaner and more manageable asynchronous code when making Axios requests. -- **Optimize with Request Interceptors**: Utilize request interceptors for tasks like adding authentication tokens, logging requests, or transforming request data. Response interceptors can be used for error handling or data transformation. -- **Ensure HTTP Requests When Necessary**: Verify that requests are only made when truly needed, preventing unnecessary network traffic and improving performance. Consider caching strategies. +# Axios Best Practices -### 1. Code Organization and Structure: +Axios is a powerful, promise-based HTTP client for browsers and Node.js. Adhering to best practices ensures maintainable, performant, and robust API interactions in your applications. - - **Directory Structure Best Practices**: - - Create an `api` or `services` directory to house all API-related code. - - Organize API modules based on resources or features (e.g., `api/users.js`, `api/products.js`). - - Separate Axios instance configuration into a dedicated file (e.g., `api/axios-config.js`). +## 1. Code Organization and Structure - - **File Naming Conventions**: - - Use descriptive names for API modules (e.g., `userApi.js`, `productService.js`). - - Follow a consistent naming convention (e.g., camelCase for variables, PascalCase for components). +- **Centralize Configuration with Axios Instances:** Always create dedicated Axios instances using `axios.create()` to centralize common configurations like `baseURL`, `timeout`, and default `headers`. This reduces boilerplate and ensures consistency across your application. - - **Module Organization**: - - Export individual API functions from each module (e.g., `getUser`, `createUser`). - - Use named exports for better code readability and maintainability. + javascript + // api.js or http-client.js + import axios from 'axios'; - - **Component Architecture**: - - Create reusable components for handling data fetching and display. - - Decouple components from specific API calls to improve reusability. - - Utilize custom hooks to encapsulate data fetching logic. + export const apiClient = axios.create({ + baseURL: import.meta.env.VITE_API_URL || 'http://localhost:3000/api', + timeout: 8000, // Request timeout in milliseconds + headers: { + 'Content-Type': 'application/json', + }, + }); + - - **Code Splitting Strategies**: - - Implement lazy loading for API modules that are not immediately required. - - Use dynamic imports to load modules on demand. - - Consider route-based code splitting for larger applications. +- **Dedicated API Modules/Services:** Organize your API calls into separate modules or service files, following the Single Responsibility Principle. Each module should handle requests for a specific resource or feature. -### 2. Common Patterns and Anti-patterns: + javascript + // services/userService.js + import { apiClient } from '../api'; - - **Design Patterns Specific to Axios**: - - **Singleton Pattern**: Use a singleton pattern for the Axios instance to ensure a single configuration across the application. - - **Adapter Pattern**: Create an adapter layer to transform API responses into a consistent format. - - **Factory Pattern**: Use a factory pattern to create different Axios instances with specific configurations. + export const userService = { + getAllUsers: () => apiClient.get('/users'), + getUserById: (id) => apiClient.get(`/users/${id}`), + createUser: (userData) => apiClient.post('/users', userData), + updateUser: (id, userData) => apiClient.put(`/users/${id}`, userData), + deleteUser: (id) => apiClient.delete(`/users/${id}`), + }; - - **Recommended Approaches for Common Tasks**: - - **Authentication**: Use request interceptors to add authentication headers (e.g., JWT tokens). - - **Error Handling**: Implement a centralized error handling function to log errors and display user-friendly messages. - - **Data Transformation**: Use response interceptors to transform data before it reaches the components. + // In a component or business logic: + // import { userService } from '../services/userService'; + // const users = await userService.getAllUsers(); + - - **Anti-patterns and Code Smells to Avoid**: - - **Hardcoding URLs**: Avoid hardcoding API endpoints directly in the code. - - **Duplicated Request Logic**: Don't repeat API request logic across multiple components. - - **Ignoring Errors**: Never ignore errors returned by Axios; always handle them appropriately. +- **Leverage Interceptors for Global Logic:** Use request and response interceptors to centralize cross-cutting concerns like authentication, logging, error handling, and data transformation. - - **State Management Best Practices**: - - Use a state management library (e.g., Redux, Zustand, Recoil) to manage API data. - - Store API responses in a normalized format to improve performance. - - Utilize selectors to derive data from the store efficiently. + javascript + // In api.js or http-client.js, after creating apiClient - - **Error Handling Patterns**: - - Implement a global error boundary to catch unexpected errors. - - Display user-friendly error messages based on the error type. - - Log errors to a central logging service for monitoring and debugging. + // Request Interceptor: Add authentication token + apiClient.interceptors.request.use( + (config) => { + const token = localStorage.getItem('jwt'); + if (token) { + config.headers.Authorization = `Bearer ${token}`; + } + // Log outgoing request (optional) + console.log(`[Axios] ${config.method.toUpperCase()} ${config.url}`); + return config; + }, + (error) => { + return Promise.reject(error); + } + ); -### 3. Performance Considerations: + // Response Interceptor: Unified error handling and response transformation + apiClient.interceptors.response.use( + (response) => { + // You can transform response data here if needed + return response; + }, + (error) => { + if (error.response) { + // The request was made and the server responded with a status code + // that falls out of the range of 2xx + console.error('[Axios Error] Status:', error.response.status, 'Data:', error.response.data); + if (error.response.status === 401) { + // Handle unauthorized errors, e.g., redirect to login + console.error('Unauthorized: Redirecting to login...'); + // window.location.href = '/login'; + } + // You can throw a custom error here for more specific handling in components + return Promise.reject(new Error(error.response.data.message || 'An API error occurred.')); + } else if (error.request) { + // The request was made but no response was received + console.error('[Axios Error] No response received:', error.request); + return Promise.reject(new Error('No response from server. Please check your network connection.')); + } else { + // Something happened in setting up the request that triggered an Error + console.error('[Axios Error] Request setup error:', error.message); + return Promise.reject(new Error('An unexpected error occurred.')); + } + } + ); + - - **Optimization Techniques**: - - **Caching**: Implement caching mechanisms to avoid redundant API calls. - - **Request Debouncing**: Debounce frequent API requests to reduce server load. - - **Request Cancellation**: Cancel pending requests when the component unmounts or the user navigates away. +## 2. Common Patterns and Anti-patterns - - **Memory Management**: - - Clear Axios instances when they are no longer needed. - - Avoid creating unnecessary Axios instances. +- **Pattern: Use `async/await`:** Prefer `async/await` for cleaner, more readable asynchronous code over `.then().catch()` chains, especially when dealing with multiple sequential requests or complex logic. - - **Rendering Optimization**: - - Use memoization techniques to prevent unnecessary re-renders. - - Implement pagination or virtualized lists for large datasets. + javascript + // Good: Using async/await + async function fetchUserData(userId) { + try { + const response = await apiClient.get(`/users/${userId}`); + return response.data; + } catch (error) { + console.error('Failed to fetch user data:', error.message); + throw error; // Re-throw to allow further handling + } + } + - - **Bundle Size Optimization**: - - Use tree shaking to remove unused code from the Axios library. - - Minify and compress the JavaScript bundle. +- **Pattern: Request Cancellation with `AbortController`:** For long-running requests or when a component might unmount before a request completes, use `AbortController` to cancel requests. This prevents memory leaks and unnecessary network activity. - - **Lazy Loading Strategies**: - - Lazy load API modules that are not immediately required. - - Use dynamic imports to load modules on demand. + javascript + // In a React component's useEffect or similar lifecycle hook + useEffect(() => { + const controller = new AbortController(); + const signal = controller.signal; -### 4. Security Best Practices: + async function fetchData() { + try { + const response = await apiClient.get('/data', { signal }); + console.log(response.data); + } catch (error) { + if (axios.isCancel(error)) { + console.log('Request cancelled:', error.message); + } else { + console.error('Error fetching data:', error.message); + } + } + } - - **Common Vulnerabilities and How to Prevent Them**: - - **Cross-Site Scripting (XSS)**: Sanitize user input to prevent XSS attacks. - - **Cross-Site Request Forgery (CSRF)**: Implement CSRF protection mechanisms. - - **Man-in-the-Middle (MITM) Attacks**: Use HTTPS to encrypt communication between the client and the server. + fetchData(); - - **Input Validation**: - - Validate user input on both the client and server sides. - - Use appropriate validation libraries to prevent injection attacks. + return () => { + // Abort the request if the component unmounts + controller.abort(); + }; + }, []); + - - **Authentication and Authorization Patterns**: - - Use a secure authentication protocol (e.g., OAuth 2.0, OpenID Connect). - - Implement role-based access control (RBAC) to restrict access to sensitive data. +- **Anti-pattern: Direct `axios` calls everywhere:** Avoid `import axios from 'axios';` and then calling `axios.get()` directly in multiple places without using a configured instance. This leads to scattered configuration and makes global changes difficult. - - **Data Protection Strategies**: - - Encrypt sensitive data at rest and in transit. - - Use appropriate data masking techniques to protect sensitive information. +- **Anti-pattern: Ignoring errors:** Always include `catch` blocks or implement comprehensive error handling via response interceptors. Unhandled promise rejections can lead to silent failures or crashes. - - **Secure API Communication**: - - Use HTTPS for all API communication. - - Implement rate limiting to prevent abuse. - - Monitor API traffic for suspicious activity. +- **Anti-pattern: Hardcoding sensitive information:** Never hardcode `baseURL`, API keys, or other sensitive credentials directly in your code. Use environment variables (e.g., `process.env.VITE_API_URL` for Vite, `process.env.REACT_APP_API_URL` for Create React App, or `.env` files for Node.js). -### 5. Testing Approaches: +## 3. Performance Considerations - - **Unit Testing Strategies**: - - Mock Axios requests using libraries like `axios-mock-adapter` or `nock`. - - Test individual API functions in isolation. - - Verify that requests are made with the correct parameters and headers. +- **Set Request Timeouts:** Always configure a `timeout` on your Axios instances or individual requests. This prevents requests from hanging indefinitely, especially in cases of network issues or unresponsive servers. - - **Integration Testing**: - - Test the interaction between API modules and components. - - Verify that data is fetched and displayed correctly. - - Use a testing framework like Jest or Mocha. + javascript + const apiClient = axios.create({ + timeout: 10000, // 10 seconds + }); + - - **End-to-End Testing**: - - Test the entire application workflow from the user's perspective. - - Use a testing framework like Cypress or Selenium. +- **Combine `timeout` with `AbortSignal`:** Understand that `timeout` handles the time until a response is received, while `AbortSignal` allows for explicit cancellation of the underlying connection. For robust control, use both. - - **Test Organization**: - - Organize tests by module or feature. - - Use descriptive names for test cases. - - Follow a consistent testing style. + javascript + axios.get('/long-request', { + timeout: 5000, // Response timeout + signal: AbortSignal.timeout(10000) // Connection timeout after 10 seconds (Node.js 17.3+) + }); + - - **Mocking and Stubbing**: - - Use mocking to isolate components from external dependencies. - - Use stubbing to replace API responses with predefined data. +- **Client-Side Caching:** For frequently accessed data that doesn't change often, consider implementing client-side caching strategies (e.g., using libraries like `React Query`, `SWR`, or a custom in-memory cache). This reduces redundant network requests and improves perceived performance. -### 6. Common Pitfalls and Gotchas: +- **Request Throttling/Debouncing:** For user interactions that trigger frequent API calls (e.g., search input, scroll events), implement throttling or debouncing to limit the rate of requests sent to the server. This prevents overloading the backend and improves client-side responsiveness. - - **Frequent Mistakes Developers Make**: - - Forgetting to handle errors. - - Using incorrect HTTP methods. - - Hardcoding URLs. - - Not setting appropriate headers. +- **Minimize Bundle Size (Contextual):** While Axios is generally lightweight, for extremely small applications where every byte counts, the native `Fetch API` might be considered. However, Axios's features (interceptors, automatic JSON parsing, error handling) often justify its inclusion for most projects. - - **Edge Cases to Be Aware Of**: - - Network errors. - - Server downtime. - - Rate limiting. - - API versioning. +## 4. Common Pitfalls and Gotchas - - **Version-Specific Issues**: - - Be aware of breaking changes between Axios versions. - - Consult the Axios documentation for specific version information. +- **Forgetting to Return in Interceptors:** Request and response interceptors *must* return the `config` or `response` object, respectively, or a `Promise.reject(error)` for error handlers. Failing to do so will halt the request/response chain. - - **Compatibility Concerns**: - - Ensure that Axios is compatible with the target browsers and environments. - - Use polyfills if necessary. +- **`cancelToken` is Deprecated:** Avoid using `axios.CancelToken`. The modern and recommended approach for request cancellation is `AbortController`. - - **Debugging Strategies**: - - Use the browser's developer tools to inspect network requests. - - Log Axios requests and responses to the console. - - Use a debugging tool like VS Code's debugger. +- **Misunderstanding `timeout` vs. `AbortSignal`:** As mentioned, `timeout` is for response time, `AbortSignal` is for connection cancellation. Use both for comprehensive control. -### 7. Tooling and Environment: +- **CORS Issues:** Cross-Origin Resource Sharing (CORS) errors are common when the frontend and backend are on different domains. While primarily a backend configuration issue, ensure your frontend sends necessary headers (e.g., `Authorization`) that the backend expects for CORS preflight requests. - - **Recommended Development Tools**: - - VS Code with the ESLint and Prettier extensions. - - Axios DevTools for Chrome and Firefox. - - Postman or Insomnia for testing API endpoints. +- **Incorrect `Content-Type` for `POST`/`PUT`:** Axios automatically sets `Content-Type: application/json` for plain JavaScript objects. However, for other data types (e.g., `FormData` for file uploads), ensure you explicitly set the correct `Content-Type` header if Axios doesn't handle it automatically. - - **Build Configuration**: - - Use a build tool like Webpack or Parcel to bundle the application. - - Configure the build tool to optimize the bundle size. +- **Handling Different Error Structures:** APIs can return errors in various formats. Your response interceptor should be robust enough to parse different error structures (e.g., `error.response.data.message`, `error.response.data.errors`). - - **Linting and Formatting**: - - Use ESLint with a consistent set of rules to enforce code quality. - - Use Prettier to format the code automatically. +## 5. Testing Approaches - - **Deployment Best Practices**: - - Deploy the application to a secure hosting environment. - - Configure HTTPS for all API communication. - - Monitor the application for errors and performance issues. +- **Mocking API Responses:** For unit and integration tests, avoid making actual network requests. Use mocking libraries to simulate API responses. - - **CI/CD Integration**: - - Integrate automated testing and deployment into the CI/CD pipeline. - - Use a CI/CD tool like Jenkins, GitLab CI, or CircleCI. \ No newline at end of file + - **`axios-mock-adapter`:** A popular library specifically designed for mocking Axios requests. It allows you to define expected requests and return mock responses. + + javascript + import axios from 'axios'; + import MockAdapter from 'axios-mock-adapter'; + import { userService } from '../services/userService'; // Your API service + + const mock = new MockAdapter(axios); // Or new MockAdapter(apiClient); + + describe('User Service', () => { + afterEach(() => { + mock.reset(); // Reset mocks after each test + }); + + test('should fetch all users', async () => { + const mockUsers = [{ id: 1, name: 'Alice' }]; + mock.onGet('/users').reply(200, mockUsers); + + const users = await userService.getAllUsers(); + expect(users.data).toEqual(mockUsers); + }); + + test('should handle fetch error', async () => { + mock.onGet('/users').reply(500, { message: 'Server Error' }); + + await expect(userService.getAllUsers()).rejects.toThrow('An API error occurred.'); + }); + }); + + + - **`MSW (Mock Service Worker)`:** A more powerful alternative that intercepts network requests at the service worker level (browser) or Node.js level. This allows for realistic mocking that works across different HTTP clients (Axios, Fetch, etc.) and is great for end-to-end testing scenarios. + +- **Unit Test API Service Functions:** Write tests for your individual API service functions to ensure they construct the correct URLs, methods, and data payloads. + +- **Test Interceptors:** Ensure your request and response interceptors behave as expected, e.g., that authentication tokens are added, and error responses are handled gracefully. \ No newline at end of file diff --git a/rules-mdc/react.mdc b/rules-mdc/react.mdc index a8802bc..f3d6a3f 100644 --- a/rules-mdc/react.mdc +++ b/rules-mdc/react.mdc @@ -1,284 +1,146 @@ --- -description: Comprehensive guide to React best practices, covering code organization, performance, security, testing, and common pitfalls. Adhering to these guidelines helps developers build maintainable, scalable, and high-performing React applications. -globs: *.js,*.jsx,*.ts,*.tsx +description: Provides comprehensive best practices for writing clean, performant, and maintainable React applications, covering code organization, common patterns, performance, state management, and accessibility. +globs: **/*.{jsx,tsx} --- -# React Best Practices: A Comprehensive Guide +# React Best Practices -This document outlines the best practices for developing React applications, covering various aspects from code organization to security and testing. Following these guidelines leads to more maintainable, scalable, and performant applications. +This guide outlines best practices for developing robust, scalable, and maintainable React applications. Adhering to these principles will lead to more predictable code, easier debugging, and improved collaboration. ## 1. Code Organization and Structure -### 1.1 Directory Structure - -A well-defined directory structure is crucial for maintainability. Here's a recommended structure: - - -src/ - ├── components/ - │ ├── Button/ - │ │ ├── Button.jsx - │ │ ├── Button.module.css - │ │ └── Button.test.jsx - │ ├── Input/ - │ │ ├── Input.jsx - │ │ ├── Input.module.css - │ │ └── Input.test.jsx - │ └── ... - ├── contexts/ - │ ├── AuthContext.jsx - │ └── ThemeContext.jsx - ├── hooks/ - │ ├── useAuth.js - │ └── useTheme.js - ├── pages/ - │ ├── Home.jsx - │ ├── About.jsx - │ └── ... - ├── services/ - │ ├── api.js - │ └── auth.js - ├── utils/ - │ ├── helpers.js - │ └── validators.js - ├── App.jsx - ├── index.jsx - └── ... - - -- **`components/`**: Reusable UI components. - - Each component has its own directory containing the component file, associated styles (using CSS modules), and tests. -- **`contexts/`**: React context providers. -- **`hooks/`**: Custom React hooks. -- **`pages/`**: Top-level components representing different routes or views. -- **`services/`**: API interaction logic. -- **`utils/`**: Utility functions. - -### 1.2 File Naming Conventions - -- **Components**: Use PascalCase (e.g., `MyComponent.jsx`). -- **Hooks**: Use camelCase prefixed with `use` (e.g., `useMyHook.js`). -- **Contexts**: Use PascalCase suffixed with `Context` (e.g., `MyContext.jsx`). -- **Services/Utils**: Use camelCase (e.g., `apiService.js`, `stringUtils.js`). -- **CSS Modules**: Use `.module.css` or `.module.scss` (e.g., `Button.module.css`). - -### 1.3 Module Organization - -- **Co-location**: Keep related files (component, styles, tests) together in the same directory. -- **Single Responsibility**: Each module should have a clear and specific purpose. -- **Avoid Circular Dependencies**: Ensure modules don't depend on each other in a circular manner. - -### 1.4 Component Architecture - -- **Atomic Design**: Consider using Atomic Design principles (Atoms, Molecules, Organisms, Templates, Pages) to structure components. -- **Composition over Inheritance**: Favor component composition to reuse code and functionality. -- **Presentational and Container Components**: Separate UI rendering (presentational) from state management and logic (container). - -### 1.5 Code Splitting Strategies - -- **Route-Based Splitting**: Use `React.lazy` and `Suspense` to load components only when a specific route is accessed. This is very common and improves initial load time. -- **Component-Based Splitting**: Split large components into smaller chunks that can be loaded on demand. -- **Bundle Analyzer**: Use a tool like `webpack-bundle-analyzer` to identify large dependencies and optimize bundle size. +* **One Component Per File:** Generally, each React component should reside in its own file. For very small, stateless, or pure components that are tightly coupled, multiple components can be in one file. + * **Naming:** Use `PascalCase` for component files (e.g., `Button.jsx`, `UserProfile.tsx`) and `camelCase` for variables and functions. +* **Functional Components & Hooks:** Prefer functional components and React Hooks (`useState`, `useEffect`, `useContext`, `useReducer`, custom hooks) over class components for new development. +* **Sensible Folder Structure:** + * Start with a flat `src/` and evolve as the project grows. + * Common structure: + ``` + src/ + ├── assets/ # Images, icons, fonts + ├── components/ # Reusable UI components (e.g., Button, Modal) + ├── features/ # Domain-specific features (e.g., Auth, Products, UserProfile) + ├── hooks/ # Custom React Hooks + ├── pages/ # Top-level page components (e.g., HomePage, DashboardPage) + ├── api/ # API service calls + ├── utils/ # Utility functions (e.g., formatters, validators) + ├── types/ # TypeScript type definitions + ├── routes/ # Application routing configuration + ├── store/ # Global state management (if applicable) + └── App.jsx + ``` +* **CSS Modules:** Use CSS Modules (`*.module.css`) or styled-components for encapsulated styling to prevent style conflicts. +* **Colocate Tests:** Place unit tests (`*.test.js` or `*.spec.js`) alongside the component files they test. ## 2. Common Patterns and Anti-patterns -### 2.1 Design Patterns +### Patterns +* **Custom Hooks:** Extract reusable stateful logic into custom hooks. + ```jsx + // hooks/useToggle.js + import { useState, useCallback } from 'react'; + const useToggle = (initialValue = false) => { + const [value, setValue] = useState(initialValue); + const toggle = useCallback(() => setValue(prev => !prev), []); + return [value, toggle]; + }; + // Usage: const [isOpen, toggleOpen] = useToggle(false); + ``` +* **Compound Components:** For complex UI patterns where components work together (e.g., `Select.Root`, `Select.Option`). +* **Context API:** Use for sharing "global" data (e.g., theme, user info) across the component tree without prop drilling. -- **Higher-Order Components (HOCs)**: Reusable logic that wraps components (use with caution; prefer hooks). -- **Render Props**: Sharing code using a prop whose value is a function. -- **Compound Components**: Components that work together implicitly (e.g., `Tabs`, `Tab`). -- **Hooks**: Reusable stateful logic that can be shared across functional components. +### Anti-patterns +* **Prop Drilling:** Avoid passing props through many layers of components that don't directly use them. Use Context API or state management libraries instead. +* **Direct DOM Manipulation:** Let React manage the DOM. Use `useRef` sparingly for direct DOM access (e.g., focusing an input). +* **Mutating State Directly:** Never directly modify state objects or arrays. Always create a new copy. + ```jsx + // BAD + // state.items.push(newItem); + // setState(state); -### 2.2 Recommended Approaches - -- **Form Handling**: Use controlled components with local state or a form library like Formik or React Hook Form. -- **API Calls**: Use `useEffect` hook to make API calls and manage loading states. -- **Conditional Rendering**: Use short-circuit evaluation (`&&`) or ternary operators for simple conditions; use separate components for complex scenarios. -- **List Rendering**: Always provide a unique and stable `key` prop when rendering lists. - -### 2.3 Anti-patterns and Code Smells - -- **Direct DOM Manipulation**: Avoid directly manipulating the DOM; let React handle updates. -- **Mutating State Directly**: Always use `setState` or the state updater function to modify state. -- **Inline Styles**: Use CSS modules or styled-components for maintainable styles. -- **Over-Engineering**: Avoid using complex solutions for simple problems. -- **Prop Drilling**: Passing props through multiple levels of components without them being used. - -### 2.4 State Management Best Practices - -- **Local State**: Use `useState` for component-specific state. -- **Context API**: Use `useContext` for global state accessible to many components, but avoid for very frequently updated data. -- **Redux/Mobx**: Use these libraries for complex state management in large applications. -- **Recoil/Zustand**: Lightweight alternatives to Redux, often easier to set up and use. -- **Immutable Data**: Treat state as immutable to prevent unexpected side effects. - -### 2.5 Error Handling Patterns - -- **Error Boundaries**: Wrap components with error boundaries to catch errors during rendering and prevent crashes. -- **Try-Catch Blocks**: Use try-catch blocks for handling errors in asynchronous operations and event handlers. -- **Centralized Error Logging**: Implement a centralized error logging service to track errors and improve application stability. + // GOOD + setItems(prevItems => [...prevItems, newItem]); + ``` +* **Complex Logic in `useEffect`:** Keep `useEffect` focused on a single side effect. Extract complex logic into separate functions or custom hooks. ## 3. Performance Considerations -### 3.1 Optimization Techniques +* **`React.memo`, `useMemo`, `useCallback`:** + * `React.memo`: Memoizes functional components to prevent re-renders if props haven't changed. Use for "pure" components with expensive render logic. + * `useMemo`: Memoizes expensive calculations. + * `useCallback`: Memoizes functions to prevent unnecessary re-creation, useful for passing stable functions to `React.memo` children or `useEffect` dependencies. + * **Caution:** Don't over-optimize. These add overhead; use them when profiling indicates a performance bottleneck. +* **Key Prop in Lists:** Always provide a unique and stable `key` prop when rendering lists of elements. Avoid using array indexes as keys if the list items can change order, be added, or removed. + ```jsx + {items.map(item => ( + + ))} + ``` +* **Lazy Loading / Code Splitting:** Use `React.lazy` and `Suspense` to split your application's code into smaller chunks, loading them only when needed. + ```jsx + const LazyComponent = React.lazy(() => import('./MyHeavyComponent')); + function App() { + return ( + Loading...}> + + + ); + } + ``` +* **Virtualization:** For very long lists, use libraries like `react-window` or `react-virtualized` to render only the visible items. -- **Memoization**: Use `React.memo`, `useMemo`, and `useCallback` to prevent unnecessary re-renders and recalculations. -- **Virtualization**: Use libraries like `react-window` or `react-virtualized` to efficiently render large lists or tables. -- **Debouncing/Throttling**: Limit the rate at which functions are executed (e.g., in input fields). -- **Code Splitting**: Load code on demand using `React.lazy` and `Suspense`. +## 4. Common Pitfalls and Gotchas -### 3.2 Memory Management +* **Incorrect `useEffect` Dependencies:** + * Missing dependencies can lead to stale closures or incorrect behavior. + * Over-specifying dependencies can lead to infinite loops or unnecessary re-runs. + * Use ESLint's `exhaustive-deps` rule. +* **Mutable Objects in State:** Modifying an object or array directly in state won't trigger a re-render because React performs a shallow comparison. Always create new objects/arrays. +* **Race Conditions in `useEffect`:** Handle asynchronous operations in `useEffect` with cleanup functions to prevent updates on unmounted components or outdated data. + ```jsx + useEffect(() => { + let didCancel = false; + async function fetchData() { + const data = await myApiCall(); + if (!didCancel) { + setData(data); + } + } + fetchData(); + return () => { didCancel = true; }; // Cleanup + }, [someDependency]); + ``` +* **Props are Read-Only:** Never modify props directly within a component. If a value needs to change, it should be managed as state in the component itself or its parent. -- **Avoid Memory Leaks**: Clean up event listeners, timers, and subscriptions in `useEffect`'s cleanup function. -- **Release Unused Objects**: Avoid holding onto large objects in memory when they are no longer needed. -- **Garbage Collection**: Understand how JavaScript's garbage collection works and avoid creating unnecessary objects. +## 5. Component Architecture -### 3.3 Rendering Optimization +* **Single Responsibility Principle:** Each component should ideally do one thing well. This makes components easier to understand, test, and reuse. +* **Presentational vs. Container Components (Smart/Dumb):** + * **Presentational (Dumb) Components:** Focus on *how things look*. Receive data and callbacks via props, have no state of their own (or only UI state), and are typically stateless functional components. + * **Container (Smart) Components:** Focus on *how things work*. Manage state, fetch data, and pass data/callbacks to presentational components. +* **Composition Over Inheritance:** React encourages composition. Build complex UIs by composing smaller, simpler components together. -- **Minimize State Updates**: Avoid unnecessary state updates that trigger re-renders. -- **Batch Updates**: Batch multiple state updates into a single update using `ReactDOM.unstable_batchedUpdates`. -- **Keys**: Ensure that keys are unique and consistent across renders. +## 6. State Management -### 3.4 Bundle Size Optimization +* **Local Component State (`useState`):** For state that is only relevant to a single component. +* **`useReducer`:** A good alternative to `useState` for more complex state logic, especially when state transitions depend on previous state or involve multiple sub-values. +* **Context API:** For sharing state or functions that are needed by many components at different nesting levels, avoiding prop drilling. +* **External Libraries (Redux, Zustand, Jotai, Recoil):** Consider these for large applications with complex global state requirements, cross-cutting concerns, or when you need advanced features like middleware, time-travel debugging, or derived state. -- **Tree Shaking**: Remove unused code during the build process. -- **Minification**: Reduce the size of JavaScript and CSS files. -- **Image Optimization**: Compress and optimize images to reduce file size. -- **Dependency Analysis**: Use tools like `webpack-bundle-analyzer` to identify large dependencies. +## 7. Accessibility (A11y) -### 3.5 Lazy Loading Strategies +* **Semantic HTML:** Use appropriate HTML elements (`