mirror of
https://github.com/sanjeed5/awesome-cursor-rules-mdc.git
synced 2026-11-30 14:52:55 +08:00
Add comprehensive MDC files for various technologies and frameworks
Generate a large set of Markdown Configuration (MDC) files covering best practices across multiple domains, including: - AI/ML libraries (PyTorch, TensorFlow, scikit-learn) - Backend frameworks (Django, FastAPI, Express, Spring Boot) - Frontend frameworks (React, Vue, Angular) - Cloud platforms (AWS, Azure, GCP) - Development tools (Docker, Kubernetes, Terraform) - State management libraries - UI component libraries - Web technologies and APIs Enhance project documentation with detailed, standardized best practice guidelines for different technologies and frameworks
This commit is contained in:
@@ -0,0 +1,169 @@
|
||||
---
|
||||
description: Enforces Next.js best practices for code organization, performance, security, and maintainability. This rule provides guidelines for structuring Next.js projects, optimizing performance, and avoiding common pitfalls.
|
||||
globs: **/*.{js,jsx,ts,tsx}
|
||||
---
|
||||
- **General Principles**
|
||||
- **Use Static Generation (SSG) or Incremental Static Regeneration (ISR) where possible.** SSG offers the best performance by pre-rendering pages at build time. ISR allows you to update static pages after build time.
|
||||
- **Optimize Images.** Use `next/image` for automatic image optimization, including resizing, format conversion, and lazy loading.
|
||||
- **Utilize API Routes.** Create API endpoints using the `pages/api` directory for serverless functions.
|
||||
- **Follow a Consistent Component Structure.** Maintain a clear and predictable component structure for reusability and maintainability.
|
||||
- **Implement Code Splitting.** Split your code into smaller chunks using dynamic imports (`next/dynamic`) to improve initial load time.
|
||||
- **Lazy Load Non-Essential Resources.** Defer loading of resources that are not critical for the initial page load.
|
||||
- **Prefer Functional Programming and Immutable Data Structures.** This can improve code readability and reduce the risk of bugs.
|
||||
- **Handle Errors Robustly.** Implement comprehensive error handling and logging throughout your application.
|
||||
|
||||
- **Code Organization and Structure**
|
||||
- **Directory Structure:**
|
||||
- `pages/`: Contains page components and API routes.
|
||||
- `components/`: Stores reusable UI components.
|
||||
- `styles/`: Holds global and component-specific CSS/SCSS modules.
|
||||
- `public/`: Static assets like images, fonts, and favicons.
|
||||
- `lib/` or `utils/`: Utility functions and helper modules.
|
||||
- `contexts/`: React Context providers for state management.
|
||||
- `hooks/`: Custom React hooks.
|
||||
- `types/` or `interfaces/`: TypeScript type definitions.
|
||||
- **File Naming Conventions:**
|
||||
- Use descriptive names for components and files (e.g., `ProductCard.tsx`, `useAuth.js`).
|
||||
- Employ camelCase for JavaScript filenames and PascalCase for component filenames.
|
||||
- Use kebab-case for CSS class names.
|
||||
- **Module Organization:**
|
||||
- Group related components and utilities into modules (e.g., `components/auth`, `utils/api`).
|
||||
- Export modules using named exports for better discoverability and tree-shaking.
|
||||
- **Component Architecture:**
|
||||
- Favor small, reusable components.
|
||||
- Use composition over inheritance.
|
||||
- Separate concerns by creating presentational (UI) and container (logic) components.
|
||||
- Utilize the `children` prop to create flexible and reusable components.
|
||||
- **Code Splitting Strategies:**
|
||||
- Use dynamic imports (`next/dynamic`) for large components or modules that are not critical for the initial page load.
|
||||
- Split code based on routes or user interactions.
|
||||
- Utilize Next.js's automatic code splitting.
|
||||
|
||||
- **Common Patterns and Anti-patterns**
|
||||
- **Design Patterns:**
|
||||
- **Higher-Order Components (HOCs):** For cross-cutting concerns like authentication or data fetching.
|
||||
- **Render Props:** For sharing logic between components.
|
||||
- **Compound Components:** For creating complex UI elements with implicit state sharing.
|
||||
- **Recommended Approaches:**
|
||||
- **Data Fetching:** Use `getStaticProps`, `getServerSideProps`, or `getInitialProps` (legacy) for data fetching.
|
||||
- **State Management:** Consider using React Context, Zustand, Redux Toolkit, or Jotai for managing application state.
|
||||
- **Routing:** Utilize `next/link` for client-side navigation and `next/router` for programmatic routing.
|
||||
- **Anti-patterns:**
|
||||
- **Direct DOM Manipulation:** Avoid manipulating the DOM directly; use React's state and props instead.
|
||||
- **Global CSS Conflicts:** Use CSS Modules or CSS-in-JS to prevent style conflicts.
|
||||
- **Over-fetching Data:** Fetch only the data that is needed by the component.
|
||||
- **Unnecessary Re-renders:** Optimize component rendering using `React.memo` or `useMemo`.
|
||||
- **State Management Best Practices:**
|
||||
- Choose a state management solution that fits the complexity of your application.
|
||||
- Centralize state that is shared between multiple components.
|
||||
- Use immutable data structures to avoid unexpected side effects.
|
||||
- Use selectors to derive data from the state.
|
||||
- **Error Handling Patterns:**
|
||||
- Use `try...catch` blocks to handle errors gracefully.
|
||||
- Implement error boundaries to prevent crashes in production.
|
||||
- Log errors to a monitoring service for debugging.
|
||||
- Display user-friendly error messages.
|
||||
|
||||
- **Performance Considerations**
|
||||
- **Optimization Techniques:**
|
||||
- **Minimize JavaScript Bundle Size:** Remove unused code, use tree-shaking, and compress your code.
|
||||
- **Optimize Third-Party Libraries:** Choose lightweight alternatives or lazy-load libraries.
|
||||
- **Cache API Responses:** Use caching to reduce the load on your API servers.
|
||||
- **Use a CDN:** Serve static assets from a Content Delivery Network (CDN).
|
||||
- **Memory Management:**
|
||||
- **Avoid Memory Leaks:** Clean up event listeners and timers when components unmount.
|
||||
- **Use Efficient Data Structures:** Choose data structures that are appropriate for the task.
|
||||
- **Rendering Optimization:**
|
||||
- **Use `React.memo`:** Prevent unnecessary re-renders of components.
|
||||
- **Virtualize Long Lists:** Render only the visible items in a long list to improve performance.
|
||||
- **Defer Expensive Calculations:** Use `useMemo` or `useCallback` to memoize expensive calculations.
|
||||
- **Bundle Size Optimization:**
|
||||
- **Analyze Bundle Size:** Use tools like `webpack-bundle-analyzer` to identify large dependencies.
|
||||
- **Remove Unused Dependencies:** Remove dependencies that are not being used.
|
||||
- **Use Code Splitting:** Split your code into smaller chunks to reduce initial load time.
|
||||
- **Lazy Loading Strategies:**
|
||||
- **Lazy Load Images:** Use `next/image` with the `lazy` loading prop.
|
||||
- **Lazy Load Components:** Use `next/dynamic` to lazy load components.
|
||||
- **Lazy Load Data:** Fetch data only when it is needed.
|
||||
|
||||
- **Security Best Practices**
|
||||
- **Common Vulnerabilities:**
|
||||
- **Cross-Site Scripting (XSS):** Sanitize user input to prevent XSS attacks.
|
||||
- **Cross-Site Request Forgery (CSRF):** Use CSRF tokens to protect against CSRF attacks.
|
||||
- **SQL Injection:** Use parameterized queries or an ORM to prevent SQL injection attacks.
|
||||
- **Authentication and Authorization Vulnerabilities:** Implement secure authentication and authorization mechanisms.
|
||||
- **Input Validation:**
|
||||
- **Validate all user input:** Ensure that the input is of the expected type and format.
|
||||
- **Sanitize user input:** Remove or escape potentially harmful characters.
|
||||
- **Authentication and Authorization Patterns:**
|
||||
- **Use a secure authentication provider:** Consider using a third-party authentication provider like Auth0 or Firebase Authentication.
|
||||
- **Implement role-based access control (RBAC):** Restrict access to resources based on user roles.
|
||||
- **Use JSON Web Tokens (JWTs) for authentication:** JWTs are a secure and stateless way to authenticate users.
|
||||
- **Data Protection Strategies:**
|
||||
- **Encrypt sensitive data:** Encrypt data at rest and in transit.
|
||||
- **Use HTTPS:** Use HTTPS to encrypt communication between the client and server.
|
||||
- **Store passwords securely:** Use a strong hashing algorithm to store passwords.
|
||||
- **Secure API Communication:**
|
||||
- **Use API keys or tokens for authentication:** Require API keys or tokens for all API requests.
|
||||
- **Rate limit API requests:** Prevent abuse by limiting the number of requests that can be made from a single IP address.
|
||||
- **Validate API requests:** Ensure that the API requests are valid and authorized.
|
||||
|
||||
- **Testing Approaches**
|
||||
- **Unit Testing Strategies:**
|
||||
- **Test individual components and functions in isolation.**
|
||||
- **Use mocking and stubbing to isolate dependencies.**
|
||||
- **Write tests for different scenarios and edge cases.**
|
||||
- **Integration Testing:**
|
||||
- **Test the interaction between multiple components or modules.**
|
||||
- **Test data flow and state management.**
|
||||
- **End-to-End Testing:**
|
||||
- **Test the entire application flow from the user's perspective.**
|
||||
- **Use tools like Cypress or Playwright for end-to-end testing.**
|
||||
- **Test Organization:**
|
||||
- **Keep tests close to the code they are testing.**
|
||||
- **Use a consistent naming convention for tests.**
|
||||
- **Organize tests into logical groups.**
|
||||
- **Mocking and Stubbing:**
|
||||
- **Use mocking to replace external dependencies with mock objects.**
|
||||
- **Use stubbing to replace functions with predefined return values.**
|
||||
|
||||
- **Common Pitfalls and Gotchas**
|
||||
- **Frequent Mistakes:**
|
||||
- **Forgetting to handle errors.**
|
||||
- **Over-complicating state management.**
|
||||
- **Not optimizing images.**
|
||||
- **Not securing API routes.**
|
||||
- **Edge Cases:**
|
||||
- **Handling different screen sizes and devices.**
|
||||
- **Dealing with slow network connections.**
|
||||
- **Handling unexpected user input.**
|
||||
- **Version-Specific Issues:**
|
||||
- **Breaking changes in Next.js updates.**
|
||||
- **Compatibility issues with third-party libraries.**
|
||||
- **Compatibility Concerns:**
|
||||
- **Browser compatibility issues.**
|
||||
- **Accessibility issues.**
|
||||
- **Debugging Strategies:**
|
||||
- **Use the browser's developer tools to debug JavaScript code.**
|
||||
- **Use the Next.js devtools extension for debugging Next.js applications.**
|
||||
- **Use logging to track the flow of execution and identify errors.**
|
||||
|
||||
- **Tooling and Environment**
|
||||
- **Recommended Development Tools:**
|
||||
- **VS Code:** A popular code editor with excellent support for JavaScript and TypeScript.
|
||||
- **ESLint:** A linter for identifying and fixing code style issues.
|
||||
- **Prettier:** A code formatter for automatically formatting code.
|
||||
- **Webpack Bundle Analyzer:** A tool for analyzing the size of your JavaScript bundles.
|
||||
- **Build Configuration:**
|
||||
- **Configure Webpack to optimize your code for production.**
|
||||
- **Use environment variables to configure your application for different environments.**
|
||||
- **Linting and Formatting:**
|
||||
- **Use ESLint and Prettier to enforce a consistent code style.**
|
||||
- **Configure your editor to automatically format code on save.**
|
||||
- **Deployment Best Practices:**
|
||||
- **Deploy your application to a platform like Vercel or Netlify.**
|
||||
- **Use environment variables to configure your application for production.**
|
||||
- **Monitor your application for errors and performance issues.**
|
||||
- **CI/CD Integration:**
|
||||
- **Use a CI/CD pipeline to automate the build, test, and deployment process.**
|
||||
- **Integrate your linting and formatting tools into your CI/CD pipeline.**
|
||||
@@ -0,0 +1,203 @@
|
||||
---
|
||||
description: This rule provides comprehensive best practices for developing React applications with Mobx, covering code organization, performance, testing, and security considerations. It aims to guide developers in building robust and maintainable applications using React-Mobx.
|
||||
globs: **/*.{js,jsx,ts,tsx}
|
||||
---
|
||||
# React-Mobx Best Practices
|
||||
|
||||
This document outlines best practices for developing React applications with Mobx. Following these guidelines will help you build robust, maintainable, and performant applications.
|
||||
|
||||
## 1. Core Principles
|
||||
|
||||
- **Model observable state:** Define the source of truth in your Mobx stores and make them observable.
|
||||
- **Use derived state (computed properties):** Derive data from your observable state using `computed` properties to avoid unnecessary re-renders and ensure data consistency.
|
||||
- **Embrace mutability:** Mobx encourages direct mutation of observable state within actions.
|
||||
- **Use strict mode:** Enforce predictable state changes by using `use strict` or enabling strict mode in Mobx to ensure all state modifications happen within actions.
|
||||
- **Keep actions in MobX stores:** Encapsulate state mutations within Mobx actions to ensure data integrity and simplify debugging.
|
||||
- **Prefer class vs object syntax:** Use class syntax for creating stores as it offers better structure, inheritance, and maintainability.
|
||||
- **Inject store rather than importing:** Use dependency injection (e.g., React Context) to provide stores to components instead of importing them directly to improve testability and reduce tight coupling.
|
||||
|
||||
## 2. Code Organization and Structure
|
||||
|
||||
- **Directory Structure:**
|
||||
- `/src`:
|
||||
- `/components`: React components (presentational and container components).
|
||||
- `/stores`: Mobx stores containing observable state and actions.
|
||||
- `/models`: Data models and types definitions.
|
||||
- `/services`: API clients and other services.
|
||||
- `/utils`: Utility functions.
|
||||
- `/hooks`: Custom React hooks.
|
||||
- `/constants`: Application-wide constants.
|
||||
- `/test`: Unit, integration, and end-to-end tests.
|
||||
|
||||
- **File Naming Conventions:**
|
||||
- Components: `ComponentName.jsx` or `ComponentName.tsx`
|
||||
- Stores: `StoreName.store.js` or `StoreName.store.ts`
|
||||
- Models: `ModelName.model.js` or `ModelName.model.ts`
|
||||
- Services: `ServiceName.service.js` or `ServiceName.service.ts`
|
||||
- Hooks: `useHookName.js` or `useHookName.ts`
|
||||
|
||||
- **Module Organization:**
|
||||
- Group related components, stores, and models into modules.
|
||||
- Use clear and descriptive module names.
|
||||
- Avoid circular dependencies between modules.
|
||||
|
||||
- **Component Architecture:**
|
||||
- **Presentational Components:** Responsible for rendering UI and receiving data via props.
|
||||
- **Container Components:** Connect presentational components to Mobx stores and manage state updates.
|
||||
- Use the `observer` decorator/function from `mobx-react-lite` to make components react to observable changes.
|
||||
|
||||
- **Code Splitting Strategies:**
|
||||
- Use React's `lazy` and `Suspense` components for lazy loading routes or components.
|
||||
- Implement route-based code splitting to load only necessary code for the current route.
|
||||
- Consider using `dynamic imports` for on-demand loading of modules.
|
||||
|
||||
## 3. Common Patterns and Anti-patterns
|
||||
|
||||
- **Design Patterns:**
|
||||
- **Observer Pattern:** Mobx uses the observer pattern to automatically update components when observable state changes.
|
||||
- **Dependency Injection:** Use React Context to inject stores into components, making them more testable and reusable.
|
||||
- **Provider Pattern:** Use a Provider component to make stores available to the component tree.
|
||||
|
||||
- **Recommended Approaches:**
|
||||
- **Form Handling:** Use Mobx to manage form state and validation.
|
||||
- **Asynchronous Operations:** Use Mobx actions to handle asynchronous operations and update the state accordingly.
|
||||
- **List Rendering:** Optimize list rendering using `key` props and `React.memo`.
|
||||
|
||||
- **Anti-patterns and Code Smells:**
|
||||
- **Modifying State Outside Actions:** Always modify observable state within Mobx actions to ensure data consistency.
|
||||
- **Deeply Nested Observables:** Avoid deeply nested observable objects as they can impact performance.
|
||||
- **Computing Data in Components:** Use `computed` properties in stores to derive data instead of computing it directly in components.
|
||||
- **Over-Observing:** Only observe the specific parts of the store that a component needs.
|
||||
|
||||
- **State Management Best Practices:**
|
||||
- **Single Source of Truth:** Keep the application state in Mobx stores and avoid duplicating data.
|
||||
- **Normalization:** Normalize data to reduce redundancy and improve data consistency.
|
||||
- **Immutability (with Mutation):** While Mobx encourages mutation, treat observable state as immutable from the perspective of components (i.e., components shouldn't directly mutate the store).
|
||||
|
||||
- **Error Handling Patterns:**
|
||||
- Implement centralized error handling using a dedicated error store.
|
||||
- Use try-catch blocks within actions to handle potential errors.
|
||||
- Display user-friendly error messages to the user.
|
||||
|
||||
## 4. Performance Considerations
|
||||
|
||||
- **Optimization Techniques:**
|
||||
- **`React.memo`:** Wrap components with `React.memo` to prevent unnecessary re-renders when props haven't changed.
|
||||
- **`useMemo` and `useCallback`:** Use `useMemo` and `useCallback` hooks to memoize values and callbacks, preventing unnecessary re-renders of child components.
|
||||
- **Computed Properties:** Use `computed` properties to derive data from observable state and cache the results.
|
||||
- **Optimize List Rendering:** Use `key` props when rendering lists and consider using virtualized lists for large datasets.
|
||||
|
||||
- **Memory Management:**
|
||||
- **Dispose of Observers:** Dispose of observers when components unmount to prevent memory leaks.
|
||||
- **Avoid Retaining Large Data Sets:** Remove or release references to large data sets when they are no longer needed.
|
||||
|
||||
- **Rendering Optimization:**
|
||||
- **Minimize Re-renders:** Optimize component rendering by using `React.memo` and avoiding unnecessary state updates.
|
||||
- **Use ShouldComponentUpdate (if needed):** In class components, use `shouldComponentUpdate` lifecycle method to control when a component should re-render. This is less common with `observer`. Be careful, can lead to bugs.
|
||||
|
||||
- **Bundle Size Optimization:**
|
||||
- **Code Splitting:** Implement code splitting to reduce the initial bundle size.
|
||||
- **Tree Shaking:** Use a bundler that supports tree shaking to remove unused code.
|
||||
- **Minification:** Minify your code to reduce the bundle size.
|
||||
|
||||
- **Lazy Loading Strategies:**
|
||||
- **React.lazy and Suspense:** Use React's built-in lazy loading mechanism.
|
||||
- **Dynamic Imports:** Use dynamic imports to load modules on demand.
|
||||
|
||||
## 5. Security Best Practices
|
||||
|
||||
- **Common Vulnerabilities:**
|
||||
- **Cross-Site Scripting (XSS):** Sanitize user inputs to prevent XSS attacks.
|
||||
- **Cross-Site Request Forgery (CSRF):** Implement CSRF protection mechanisms.
|
||||
- **Injection Attacks:** Validate user inputs to prevent SQL injection and other injection attacks.
|
||||
|
||||
- **Input Validation:**
|
||||
- **Server-Side Validation:** Always validate user inputs on the server-side.
|
||||
- **Client-Side Validation:** Implement client-side validation to provide immediate feedback to the user.
|
||||
|
||||
- **Authentication and Authorization Patterns:**
|
||||
- **JSON Web Tokens (JWT):** Use JWTs for authentication and authorization.
|
||||
- **Role-Based Access Control (RBAC):** Implement RBAC to control access to different parts of the application.
|
||||
|
||||
- **Data Protection Strategies:**
|
||||
- **Encryption:** Encrypt sensitive data both in transit and at rest.
|
||||
- **Data Masking:** Mask sensitive data to protect user privacy.
|
||||
|
||||
- **Secure API Communication:**
|
||||
- **HTTPS:** Use HTTPS for all API communication.
|
||||
- **Rate Limiting:** Implement rate limiting to prevent abuse.
|
||||
|
||||
## 6. Testing Approaches
|
||||
|
||||
- **Unit Testing Strategies:**
|
||||
- Test individual components and stores in isolation.
|
||||
- Mock dependencies to isolate the unit under test.
|
||||
- Use testing libraries like Jest and React Testing Library.
|
||||
|
||||
- **Integration Testing:**
|
||||
- Test the interaction between different components and stores.
|
||||
- Use a testing environment that closely resembles the production environment.
|
||||
|
||||
- **End-to-End Testing:**
|
||||
- Test the entire application flow from the user's perspective.
|
||||
- Use testing frameworks like Cypress or Selenium.
|
||||
|
||||
- **Test Organization:**
|
||||
- Organize tests into separate directories for unit, integration, and end-to-end tests.
|
||||
- Use descriptive test names.
|
||||
|
||||
- **Mocking and Stubbing:**
|
||||
- Use mocking libraries to mock dependencies in unit tests.
|
||||
- Use stubbing to replace complex dependencies with simpler implementations.
|
||||
|
||||
## 7. Common Pitfalls and Gotchas
|
||||
|
||||
- **Frequent Mistakes:**
|
||||
- Forgetting to decorate components with `observer`.
|
||||
- Modifying state outside of actions.
|
||||
- Not disposing of observers properly.
|
||||
- Over-observing state.
|
||||
|
||||
- **Edge Cases:**
|
||||
- Handling large datasets efficiently.
|
||||
- Dealing with complex asynchronous operations.
|
||||
- Managing nested observable objects.
|
||||
|
||||
- **Version-Specific Issues:**
|
||||
- Be aware of breaking changes in Mobx and React versions.
|
||||
- Consult the Mobx and React documentation for migration guides.
|
||||
|
||||
- **Compatibility Concerns:**
|
||||
- Ensure compatibility with different browsers and devices.
|
||||
- Test your application on different platforms.
|
||||
|
||||
- **Debugging Strategies:**
|
||||
- Use the Mobx devtools to inspect observable state and track changes.
|
||||
- Use browser developer tools to debug React components.
|
||||
- Add logging statements to track the flow of data and execution.
|
||||
|
||||
## 8. Tooling and Environment
|
||||
|
||||
- **Recommended Development Tools:**
|
||||
- **VS Code:** A popular code editor with excellent support for React and Mobx.
|
||||
- **Mobx Devtools:** A browser extension for inspecting Mobx state.
|
||||
- **React Devtools:** A browser extension for inspecting React components.
|
||||
|
||||
- **Build Configuration:**
|
||||
- **Webpack:** A popular module bundler for React applications.
|
||||
- **Parcel:** A zero-configuration bundler that's easy to use.
|
||||
- **Rollup:** A bundler focused on creating libraries and smaller bundles.
|
||||
|
||||
- **Linting and Formatting:**
|
||||
- **ESLint:** A JavaScript linter for enforcing code style and preventing errors.
|
||||
- **Prettier:** A code formatter for automatically formatting code.
|
||||
- **Husky/lint-staged:** Tools to automatically lint code before commits
|
||||
|
||||
- **Deployment Best Practices:**
|
||||
- **Continuous Integration/Continuous Deployment (CI/CD):** Automate the build, test, and deployment process.
|
||||
- **Caching:** Use caching to improve performance.
|
||||
- **Content Delivery Network (CDN):** Use a CDN to serve static assets.
|
||||
|
||||
- **CI/CD Integration:**
|
||||
- Integrate your application with a CI/CD pipeline to automate the build, test, and deployment process.
|
||||
- Use tools like Jenkins, Travis CI, or CircleCI.
|
||||
@@ -0,0 +1,196 @@
|
||||
---
|
||||
description: This rule provides comprehensive guidelines for React Native development, covering code organization, performance, security, testing, and common pitfalls. Adhering to these practices ensures maintainable, scalable, and efficient React Native applications.
|
||||
globs: **/*.{js,jsx,ts,tsx}
|
||||
---
|
||||
# React Native Best Practices
|
||||
|
||||
This document outlines best practices for developing React Native applications, covering various aspects from code organization to performance optimization.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
* **Directory Structure:**
|
||||
* Adopt a scalable and maintainable directory structure. Feature-based organization is often preferred.
|
||||
* Example:
|
||||
|
||||
src/
|
||||
├── components/ # Reusable UI components
|
||||
├── screens/ # App screens/views
|
||||
├── navigation/ # Navigation configurations
|
||||
├── services/ # API services and data fetching
|
||||
├── utils/ # Utility functions
|
||||
├── constants/ # Constant values
|
||||
├── context/ # React Context providers
|
||||
├── types/ # TypeScript type definitions
|
||||
└── App.tsx # Root component
|
||||
|
||||
* **File Naming Conventions:**
|
||||
* Use descriptive and consistent file names.
|
||||
* Components: `ComponentName.tsx` (or `.jsx`)
|
||||
* Styles: `ComponentName.styles.ts` (or `.js`)
|
||||
* Utility functions: `utilityName.ts` (or `.js`)
|
||||
* Consider using kebab-case for folders.
|
||||
* **Module Organization:**
|
||||
* Group related components, styles, and assets within the same directory.
|
||||
* Use `index.ts` (or `.js`) files to export modules, simplifying imports.
|
||||
* Example:
|
||||
|
||||
// components/Button/index.ts
|
||||
export { default as Button } from './Button';
|
||||
|
||||
* **Component Architecture:**
|
||||
* Favor functional components with hooks over class components.
|
||||
* Separate concerns using container and presentational components.
|
||||
* **Container components:** Handle data fetching and state management.
|
||||
* **Presentational components:** Focus on rendering UI based on props.
|
||||
* Use composition to create flexible and reusable components.
|
||||
* **Code Splitting Strategies:**
|
||||
* Implement lazy loading for screens and components to reduce initial bundle size.
|
||||
* Use `React.lazy` and `Suspense` for code splitting.
|
||||
* Dynamic imports can be useful for loading non-critical modules on demand.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
* **Design Patterns:**
|
||||
* **Higher-Order Components (HOCs):** Wrap components with shared logic.
|
||||
* **Render Props:** Share code between React components using a prop whose value is a function.
|
||||
* **Hooks:** Extract stateful logic into reusable functions.
|
||||
* **Compound Components:** Allow components to implicitly share state (e.g., Tabs).
|
||||
* **Recommended Approaches:**
|
||||
* **State Management:** Use appropriate state management solutions (e.g., Redux, Zustand, React Context) based on the application's complexity. For local state management, `useState` and `useReducer` hooks are preferred.
|
||||
* **API Calls:** Use `async/await` for asynchronous operations and handle errors gracefully.
|
||||
* **Navigation:** Utilize `react-navigation` or `react-native-navigation` for screen transitions and navigation logic.
|
||||
* **Anti-patterns:**
|
||||
* **Mutating state directly:** Use `setState` or state update functions from hooks.
|
||||
* **Passing too many props:** Refactor components or use context to share data.
|
||||
* **Overusing global state:** Consider component-level state when appropriate.
|
||||
* **Long functions:** Break down functions into smaller, more manageable pieces.
|
||||
* **State Management Best Practices:**
|
||||
* Choose the right state management tool for the job (Context API, Redux, Zustand, Recoil).
|
||||
* Keep state minimal and derive values when possible.
|
||||
* Use immutable data structures to simplify state updates.
|
||||
* Optimize re-renders by using `React.memo`, `useMemo`, and `useCallback`.
|
||||
* **Error Handling Patterns:**
|
||||
* Use `try/catch` blocks to handle synchronous errors.
|
||||
* Implement error boundaries to catch errors in React components.
|
||||
* Log errors to a monitoring service for tracking and analysis (e.g., Sentry, Bugsnag).
|
||||
* Provide user-friendly error messages and recovery options.
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
* **Optimization Techniques:**
|
||||
* **Memoization:** Use `React.memo` to prevent unnecessary re-renders of components.
|
||||
* **PureComponent:** Use `PureComponent` for class components to perform shallow prop comparisons.
|
||||
* **Virtualization:** Use `FlatList` or `SectionList` for rendering large lists of data efficiently.
|
||||
* **Debouncing and Throttling:** Limit the rate at which functions are executed in response to rapid events (e.g., scrolling, typing).
|
||||
* **Memory Management:**
|
||||
* Avoid memory leaks by properly cleaning up event listeners and timers in `useEffect` hooks.
|
||||
* Release resources when components unmount.
|
||||
* Be mindful of image sizes and optimize them for mobile devices.
|
||||
* **Rendering Optimization:**
|
||||
* Minimize the number of re-renders by using `useCallback` and `useMemo` to memoize functions and values.
|
||||
* Avoid inline function definitions in render methods.
|
||||
* Use `shouldComponentUpdate` (for class components) or `React.memo` to prevent unnecessary renders.
|
||||
* **Bundle Size Optimization:**
|
||||
* Use code splitting to reduce the initial bundle size.
|
||||
* Remove unused code using tree shaking.
|
||||
* Optimize image assets using tools like ImageOptim or TinyPNG.
|
||||
* Analyze bundle size using tools like `webpack-bundle-analyzer`.
|
||||
* **Lazy Loading Strategies:**
|
||||
* Implement lazy loading for images using libraries like `react-native-fast-image`.
|
||||
* Lazy load components using `React.lazy` and `Suspense`.
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
* **Common Vulnerabilities:**
|
||||
* **Cross-Site Scripting (XSS):** Prevent XSS attacks by sanitizing user input before rendering it in the UI.
|
||||
* **SQL Injection:** Use parameterized queries or ORMs to prevent SQL injection attacks.
|
||||
* **Insecure Data Storage:** Avoid storing sensitive data in plain text on the device.
|
||||
* **Man-in-the-Middle (MITM) Attacks:** Use HTTPS to encrypt communication between the app and the server.
|
||||
* **Input Validation:**
|
||||
* Validate all user input on both the client and server sides.
|
||||
* Use regular expressions to enforce input formats.
|
||||
* Sanitize input to remove potentially malicious characters.
|
||||
* **Authentication and Authorization Patterns:**
|
||||
* Use secure authentication methods like OAuth 2.0 or JWT.
|
||||
* Implement role-based access control to restrict access to sensitive data and functionality.
|
||||
* Store authentication tokens securely using the device's keychain or secure storage.
|
||||
* **Data Protection Strategies:**
|
||||
* Encrypt sensitive data at rest using encryption libraries.
|
||||
* Use secure storage options provided by the platform (e.g., Keychain on iOS, KeyStore on Android).
|
||||
* Avoid logging sensitive data.
|
||||
* **Secure API Communication:**
|
||||
* Use HTTPS for all API communication.
|
||||
* Implement proper authentication and authorization for API endpoints.
|
||||
* Protect against CSRF attacks by using anti-CSRF tokens.
|
||||
* Rate limit API requests to prevent abuse.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
* **Unit Testing:**
|
||||
* Test individual components and functions in isolation.
|
||||
* Use testing frameworks like Jest or Mocha.
|
||||
* Write tests for edge cases and error conditions.
|
||||
* **Integration Testing:**
|
||||
* Test the interaction between different components and modules.
|
||||
* Verify that data flows correctly between different parts of the application.
|
||||
* **End-to-End Testing:**
|
||||
* Test the entire application flow from start to finish.
|
||||
* Use testing frameworks like Detox or Appium.
|
||||
* Run tests on real devices or emulators.
|
||||
* **Test Organization:**
|
||||
* Organize tests in a way that mirrors the application's directory structure.
|
||||
* Use descriptive test names to clearly indicate what is being tested.
|
||||
* Keep tests small and focused.
|
||||
* **Mocking and Stubbing:**
|
||||
* Use mocking libraries like Jest's `jest.mock` to isolate components during testing.
|
||||
* Stub out dependencies to control their behavior.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
* **Frequent Mistakes:**
|
||||
* **Incorrectly using `setState`:** Understand the asynchronous nature of `setState` and use functional updates when necessary.
|
||||
* **Not optimizing images:** Large images can significantly impact performance.
|
||||
* **Ignoring memory leaks:** Failing to clean up event listeners and timers can lead to memory leaks.
|
||||
* **Over-rendering:** Unnecessary re-renders can degrade performance.
|
||||
* **Edge Cases:**
|
||||
* **Handling different screen sizes and densities:** Use responsive design techniques to adapt to various screen sizes.
|
||||
* **Dealing with network latency:** Implement loading indicators and error handling for API requests.
|
||||
* **Handling different locales and languages:** Use internationalization (i18n) libraries to support multiple languages.
|
||||
* **Version-Specific Issues:**
|
||||
* Be aware of breaking changes in React Native updates.
|
||||
* Test your application on different versions of React Native to ensure compatibility.
|
||||
* Use `react-native-upgrade-helper` to help with upgrades.
|
||||
* **Compatibility Concerns:**
|
||||
* Test your application on different devices and operating systems.
|
||||
* Be aware of platform-specific APIs and features.
|
||||
* Use conditional rendering or platform-specific code when necessary.
|
||||
* **Debugging Strategies:**
|
||||
* Use the React Native debugger to inspect component state and props.
|
||||
* Use `console.log` statements to trace code execution.
|
||||
* Use error logging to capture and track errors.
|
||||
* Learn to use the Chrome Developer Tools for debugging JavaScript code.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
* **Recommended Development Tools:**
|
||||
* **VS Code:** A popular code editor with excellent React Native support.
|
||||
* **React Native Debugger:** A standalone debugger for React Native applications.
|
||||
* **Expo CLI:** A tool for creating, building, and deploying React Native applications.
|
||||
* **Android Studio/Xcode:** The official IDEs for Android and iOS development, respectively.
|
||||
* **Build Configuration:**
|
||||
* Use environment variables to configure different build environments (e.g., development, staging, production).
|
||||
* Optimize build settings for performance.
|
||||
* **Linting and Formatting:**
|
||||
* Use ESLint and Prettier to enforce code style and prevent errors.
|
||||
* Configure ESLint with React Native-specific rules.
|
||||
* Use a pre-commit hook to automatically format code before committing.
|
||||
* **Deployment Best Practices:**
|
||||
* Use code signing to ensure the integrity of your application.
|
||||
* Follow the platform-specific deployment guidelines (e.g., Google Play Store, Apple App Store).
|
||||
* Use a continuous integration/continuous deployment (CI/CD) pipeline to automate the deployment process.
|
||||
* **CI/CD Integration:**
|
||||
* Use CI/CD tools like Jenkins, CircleCI, or GitHub Actions to automate building, testing, and deploying your application.
|
||||
* Configure CI/CD to run unit tests, integration tests, and end-to-end tests.
|
||||
* Automate the process of creating and deploying release builds.
|
||||
|
||||
By following these best practices, you can develop robust, scalable, and maintainable React Native applications.
|
||||
@@ -0,0 +1,267 @@
|
||||
---
|
||||
description: This rule enforces best practices for using react-query in React applications, covering code organization, performance, security, and testing.
|
||||
globs: **/*.{js,jsx,ts,tsx}
|
||||
---
|
||||
# react-query Best Practices
|
||||
|
||||
This document outlines the best practices for using react-query in React applications, covering various aspects such as code organization, performance considerations, security, and testing.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
### 1.1 Directory Structure Best Practices
|
||||
|
||||
* **Feature-based Organization:** Group react-query hooks and related components within feature-specific directories. This improves modularity and maintainability.
|
||||
|
||||
src/
|
||||
├── features/
|
||||
│ ├── users/
|
||||
│ │ ├── components/
|
||||
│ │ │ ├── UserList.tsx
|
||||
│ │ │ └── UserDetails.tsx
|
||||
│ │ ├── hooks/
|
||||
│ │ │ ├── useUsersQuery.ts
|
||||
│ │ │ └── useCreateUserMutation.ts
|
||||
│ │ ├── api/
|
||||
│ │ │ └── usersApi.ts
|
||||
│ │ └── types/
|
||||
│ │ └── user.ts
|
||||
│ ├── products/
|
||||
│ └── ...
|
||||
├── ...
|
||||
|
||||
|
||||
* **Dedicated API Service Layer:** Abstract API interaction logic into separate modules. This allows for easier testing and decoupling of components from specific API implementations. Consider using a dedicated `api` directory within each feature.
|
||||
|
||||
### 1.2 File Naming Conventions
|
||||
|
||||
* **Consistent Naming:** Follow a consistent naming convention for react-query hooks. Prefix hooks with `use` and postfix with `Query` or `Mutation` to clearly indicate their purpose (e.g., `usePostsQuery`, `useUpdatePostMutation`).
|
||||
|
||||
* **Descriptive Names:** Use descriptive names for files and variables to improve code readability. For example, `useFetchUsersQuery.ts` is more informative than `useUsers.ts`.
|
||||
|
||||
### 1.3 Module Organization
|
||||
|
||||
* **Custom Hooks for Reusability:** Encapsulate react-query logic within custom hooks to promote reusability and separation of concerns.
|
||||
|
||||
typescript
|
||||
// src/features/users/hooks/useUsersQuery.ts
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { fetchUsers } from '../api/usersApi';
|
||||
|
||||
export const useUsersQuery = () => {
|
||||
return useQuery('users', fetchUsers);
|
||||
};
|
||||
|
||||
|
||||
* **Separate Query and Mutation Files:** Organize queries and mutations into separate files or modules. This enhances code readability and maintainability.
|
||||
|
||||
### 1.4 Component Architecture
|
||||
|
||||
* **Presentational and Container Components:** Separate presentational components (UI) from container components (data fetching and state management). This improves testability and reusability.
|
||||
|
||||
* **Composition:** Use component composition to build complex UIs from smaller, reusable components. Leverage React Context for shared state when appropriate.
|
||||
|
||||
### 1.5 Code Splitting Strategies
|
||||
|
||||
* **Route-Based Splitting:** Split your application into separate bundles based on routes. This reduces the initial load time and improves perceived performance. React.lazy and React.Suspense can assist with this.
|
||||
|
||||
* **Component-Based Splitting:** Split large components into smaller chunks that can be loaded on demand. This can improve the performance of individual pages or components.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
### 2.1 Design Patterns Specific to react-query
|
||||
|
||||
* **Custom Hooks for Data Fetching:** As highlighted earlier, encapsulating react-query logic within custom hooks. This promotes reusability and separation of concerns. These hooks will typically return the result of a `useQuery` or `useMutation` call.
|
||||
|
||||
* **Optimistic Updates:** Implement optimistic updates to improve perceived performance. This involves updating the UI before the API request completes, and then reverting the changes if the request fails. react-query provides utilities like `onMutate` to handle this.
|
||||
|
||||
* **Pessimistic Updates:** Update the UI only after a successful response from the API. Simpler to implement but provides a less snappy user experience.
|
||||
|
||||
### 2.2 Recommended Approaches for Common Tasks
|
||||
|
||||
* **Prefetching Data:** Prefetch data for routes or components that the user is likely to visit next. This can significantly improve the user experience. Use `queryClient.prefetchQuery`.
|
||||
|
||||
* **Pagination and Infinite Scrolling:** Implement pagination and infinite scrolling to handle large datasets efficiently. react-query provides hooks like `useInfiniteQuery` to simplify this.
|
||||
|
||||
* **Dependent Queries:** Fetch data based on the result of a previous query. Use the `enabled` option in `useQuery` to conditionally execute queries.
|
||||
|
||||
typescript
|
||||
const { data: user } = useQuery(['user', userId], () => fetchUser(userId));
|
||||
|
||||
const { data: posts } = useQuery(['posts', user?.id], () => fetchPosts(user.id), {
|
||||
enabled: !!user,
|
||||
});
|
||||
|
||||
|
||||
### 2.3 Anti-patterns and Code Smells to Avoid
|
||||
|
||||
* **Directly Calling API in Components:** Avoid making API calls directly within components. This makes testing difficult and tightly couples components to specific API implementations.
|
||||
|
||||
* **Ignoring Error Handling:** Always handle errors properly. Display user-friendly error messages and provide options for retrying requests.
|
||||
|
||||
* **Over-fetching Data:** Fetch only the data that is required by the component. Use GraphQL or API query parameters to reduce the amount of data transferred.
|
||||
|
||||
* **Deeply Nested Queries:** Avoid deeply nesting queries, as this can lead to performance issues and make the code difficult to understand. Consider combining queries or using a different approach.
|
||||
|
||||
### 2.4 State Management Best Practices
|
||||
|
||||
* **Local vs. Global State:** Determine whether data should be stored in local component state or in a global state management solution. Use local state for component-specific data and global state for data that needs to be shared across multiple components.
|
||||
|
||||
* **react-query as a State Manager:** Leverage react-query's built-in caching and state management capabilities. Avoid using external state management libraries for data that is already managed by react-query.
|
||||
|
||||
### 2.5 Error Handling Patterns
|
||||
|
||||
* **Centralized Error Handling:** Implement centralized error handling to provide consistent error messages and logging.
|
||||
|
||||
* **Retry Logic:** Implement retry logic to automatically retry failed requests. react-query provides options for configuring retry behavior.
|
||||
|
||||
* **Error Boundaries:** Use Error Boundaries to catch errors that occur during rendering. This prevents the entire application from crashing.
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
### 3.1 Optimization Techniques
|
||||
|
||||
* **Query Invalidation:** Invalidate queries when data changes. This ensures that the UI is always up-to-date.
|
||||
|
||||
* **Stale-While-Revalidate:** Use the `staleTime` and `cacheTime` options to configure how long data should be considered fresh. `staleWhileRevalidate` allows the UI to display cached data while fetching fresh data in the background.
|
||||
|
||||
* **Window Focus Refetching:** Configure refetching on window focus to keep data fresh when the user switches back to the application.
|
||||
|
||||
* **Polling/Refetch Intervals:** Use `refetchInterval` to periodically refetch data. This is useful for data that changes frequently.
|
||||
|
||||
### 3.2 Memory Management
|
||||
|
||||
* **Query Cache Management:** Understand how react-query manages its cache. Configure the `cacheTime` option to control how long data is stored in the cache.
|
||||
|
||||
* **Garbage Collection:** Ensure that unused queries are garbage collected properly. Use the `gcTime` option to configure how long inactive queries should be kept in the cache.
|
||||
|
||||
### 3.3 Rendering Optimization
|
||||
|
||||
* **Memoization:** Use `React.memo` to prevent unnecessary re-renders of components. This is especially important for components that display data fetched from react-query.
|
||||
|
||||
* **Virtualization:** Use virtualization techniques (e.g., `react-window`, `react-virtualized`) to efficiently render large lists of data.
|
||||
|
||||
### 3.4 Bundle Size Optimization
|
||||
|
||||
* **Tree Shaking:** Ensure that your build process is configured for tree shaking. This removes unused code from the final bundle.
|
||||
|
||||
* **Code Splitting:** As mentioned earlier, use code splitting to reduce the initial load time.
|
||||
|
||||
### 3.5 Lazy Loading Strategies
|
||||
|
||||
* **Lazy Load Components:** Use `React.lazy` to lazy load components that are not immediately needed.
|
||||
|
||||
* **Lazy Load Data:** Fetch data only when it is needed. Use dependent queries to fetch data based on user interactions.
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
### 4.1 Common Vulnerabilities and How to Prevent Them
|
||||
|
||||
* **Cross-Site Scripting (XSS):** Sanitize user input to prevent XSS attacks. Use a library like DOMPurify to sanitize HTML.
|
||||
|
||||
* **Cross-Site Request Forgery (CSRF):** Implement CSRF protection to prevent attackers from performing actions on behalf of the user. Use a library or framework that provides CSRF protection.
|
||||
|
||||
* **Injection Attacks:** Protect against injection attacks by validating user input and using parameterized queries.
|
||||
|
||||
### 4.2 Input Validation
|
||||
|
||||
* **Client-Side Validation:** Implement client-side validation to provide immediate feedback to the user.
|
||||
|
||||
* **Server-Side Validation:** Always validate user input on the server-side to prevent malicious data from being stored in the database.
|
||||
|
||||
### 4.3 Authentication and Authorization Patterns
|
||||
|
||||
* **JSON Web Tokens (JWT):** Use JWTs for authentication. Store the JWT in a secure cookie or in local storage (with caution). Use `httpOnly` flag on cookies containing JWTs when possible to prevent client-side script access.
|
||||
|
||||
* **Role-Based Access Control (RBAC):** Implement RBAC to control access to different parts of the application. Use middleware or custom hooks to check user roles.
|
||||
|
||||
### 4.4 Data Protection Strategies
|
||||
|
||||
* **Encryption:** Encrypt sensitive data at rest and in transit. Use HTTPS to encrypt data in transit. Encrypt sensitive data in the database.
|
||||
|
||||
* **Data Masking:** Mask sensitive data in logs and reports. This prevents sensitive data from being exposed to unauthorized users.
|
||||
|
||||
### 4.5 Secure API Communication
|
||||
|
||||
* **HTTPS:** Use HTTPS for all API communication. This encrypts data in transit and prevents eavesdropping.
|
||||
|
||||
* **API Rate Limiting:** Implement API rate limiting to prevent abuse.
|
||||
|
||||
* **CORS:** Configure CORS properly to prevent cross-origin requests from unauthorized domains.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
### 5.1 Unit Testing Strategies
|
||||
|
||||
* **Test Custom Hooks:** Unit test custom react-query hooks to ensure they are working correctly. Mock the API calls using libraries like `msw` (Mock Service Worker).
|
||||
|
||||
* **Test Components in Isolation:** Unit test components in isolation to ensure they render correctly and handle user interactions properly. Use libraries like `react-testing-library`.
|
||||
|
||||
### 5.2 Integration Testing
|
||||
|
||||
* **Test Data Flow:** Integration test the data flow between components and APIs. Verify that data is fetched correctly and displayed properly.
|
||||
|
||||
* **Test Error Handling:** Integration test error handling scenarios to ensure that errors are handled properly.
|
||||
|
||||
### 5.3 End-to-End Testing
|
||||
|
||||
* **Simulate User Interactions:** Use end-to-end testing frameworks like Cypress or Playwright to simulate user interactions and verify that the application is working correctly from the user's perspective.
|
||||
|
||||
* **Test Critical Paths:** Focus on testing critical user flows, such as login, registration, and checkout.
|
||||
|
||||
### 5.4 Test Organization
|
||||
|
||||
* **Colocate Tests with Components:** Colocate tests with the components they are testing. This makes it easier to find and maintain tests.
|
||||
|
||||
* **Use Descriptive Test Names:** Use descriptive test names to clearly indicate what each test is verifying.
|
||||
|
||||
### 5.5 Mocking and Stubbing
|
||||
|
||||
* **Mock API Calls:** Use mocking libraries like `msw` to mock API calls during testing. This allows you to test components in isolation without relying on a real API.
|
||||
|
||||
* **Stub External Dependencies:** Stub external dependencies to isolate components and make tests more predictable.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
* **Forgetting to Invalidate Queries:** Failing to invalidate queries when data changes can lead to stale data being displayed in the UI.
|
||||
|
||||
* **Incorrect Cache Configuration:** Incorrectly configuring the `cacheTime` and `staleTime` options can lead to performance issues or stale data.
|
||||
|
||||
* **Not Handling Errors Properly:** Not handling errors properly can lead to unexpected behavior and a poor user experience.
|
||||
|
||||
* **Over-relying on Default Configuration:** Customizing react-query to match specific needs is essential.
|
||||
|
||||
* **Ignoring Devtools:** The react-query devtools are invaluable for debugging and understanding what is happening under the hood.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
### 7.1 Recommended Development Tools
|
||||
|
||||
* **VS Code:** Use VS Code with extensions like ESLint, Prettier, and TypeScript to improve developer productivity.
|
||||
|
||||
* **React Developer Tools:** Use the React Developer Tools browser extension to inspect React components and state.
|
||||
|
||||
* **react-query Devtools:** Use the react-query Devtools to inspect the react-query cache and track query and mutation status.
|
||||
|
||||
### 7.2 Build Configuration
|
||||
|
||||
* **Webpack or Parcel:** Use a bundler like Webpack or Parcel to bundle your code for production. Configure the bundler for tree shaking and code splitting.
|
||||
|
||||
* **Babel:** Use Babel to transpile your code to older versions of JavaScript. This ensures that your code is compatible with older browsers.
|
||||
|
||||
### 7.3 Linting and Formatting
|
||||
|
||||
* **ESLint:** Use ESLint to enforce coding standards and prevent errors. Configure ESLint to use a popular style guide like Airbnb or Google.
|
||||
|
||||
* **Prettier:** Use Prettier to automatically format your code. This ensures that your code is consistently formatted and easy to read.
|
||||
|
||||
### 7.4 Deployment Best Practices
|
||||
|
||||
* **CDN:** Use a CDN to serve static assets. This improves performance and reduces the load on your server.
|
||||
|
||||
* **Caching:** Configure caching properly on your server and CDN. This reduces the number of requests to your server and improves performance.
|
||||
|
||||
### 7.5 CI/CD Integration
|
||||
|
||||
* **Automated Testing:** Integrate automated testing into your CI/CD pipeline. This ensures that your code is tested automatically before it is deployed.
|
||||
|
||||
* **Automated Deployment:** Automate the deployment process to reduce the risk of errors and improve efficiency.
|
||||
@@ -0,0 +1,283 @@
|
||||
---
|
||||
description: Enforces best practices for structuring and maintaining React-Redux applications, focusing on code organization, performance, and maintainability. This rule provides guidelines for developers to write efficient, scalable, and testable React-Redux code.
|
||||
globs: **/*.{js,jsx,ts,tsx}
|
||||
---
|
||||
# React-Redux Best Practices
|
||||
|
||||
This document outlines best practices for developing React applications with Redux for state management. Following these guidelines will help you write maintainable, scalable, and performant code.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
### 1.1. Directory Structure
|
||||
|
||||
Organize your code around features rather than technical concerns. A feature-based directory structure promotes modularity and makes it easier to understand the application's purpose.
|
||||
|
||||
|
||||
src/
|
||||
├── app/
|
||||
│ ├── components/
|
||||
│ │ └── App.tsx
|
||||
│ └── App.css
|
||||
├── features/
|
||||
│ ├── featureName/
|
||||
│ │ ├── components/
|
||||
│ │ │ ├── FeatureComponent.tsx
|
||||
│ │ │ └── FeatureComponent.css
|
||||
│ │ ├── FeatureSlice.ts # Redux slice for the feature
|
||||
│ │ ├── FeatureSelectors.ts # Selectors for accessing feature state
|
||||
│ │ ├── FeatureActions.ts # Actions related to this feature
|
||||
│ │ └── api.ts # API calls related to the feature
|
||||
│ ├── anotherFeature/
|
||||
│ │ └── ...
|
||||
├── store.ts # Redux store configuration
|
||||
├── index.tsx # Entry point for the React application
|
||||
└── ...
|
||||
|
||||
|
||||
### 1.2. File Naming Conventions
|
||||
|
||||
* **Components:** Use PascalCase (e.g., `MyComponent.tsx`).
|
||||
* **Redux Slice Files:** Use PascalCase and end with `Slice.ts` or `Slice.js` (e.g., `UserSlice.ts`).
|
||||
* **Selectors:** `selectors.ts` or `selectors.js` or `FeatureSelectors.ts` to include a feature name prefix
|
||||
* **Actions:** `actions.ts` or `actions.js` or `FeatureActions.ts` to include a feature name prefix
|
||||
* **Styles:** Use either `ComponentName.module.css` (for CSS Modules) or `ComponentName.css` (for global styles).
|
||||
* **Utility Functions:** Use camelCase (e.g., `formatDate.ts`).
|
||||
|
||||
### 1.3. Module Organization
|
||||
|
||||
* **Encapsulation:** Each feature should be a self-contained module with its components, actions, reducers, and selectors.
|
||||
* **Single Responsibility Principle:** Each module should have a single, well-defined purpose.
|
||||
* **Clear Boundaries:** Define clear boundaries between modules to minimize dependencies and prevent tight coupling.
|
||||
|
||||
### 1.4. Component Architecture
|
||||
|
||||
* **Presentational and Container Components:**
|
||||
* **Presentational (Dumb) Components:** Focus on rendering UI and receiving data and callbacks as props. They should be reusable and independent of Redux.
|
||||
* **Container (Smart) Components:** Connect to the Redux store and pass data and actions to presentational components. Use `connect` or `useSelector` and `useDispatch` hooks.
|
||||
* **Small and Reusable Components:** Break down complex UIs into smaller, reusable components to promote code reuse and maintainability.
|
||||
* **Component Composition:** Build complex UIs by composing smaller components.
|
||||
|
||||
### 1.5. Code Splitting Strategies
|
||||
|
||||
* **Route-Based Splitting:** Split the application into chunks based on routes to reduce the initial load time. Use `React.lazy` and `Suspense` for lazy loading components.
|
||||
* **Component-Based Splitting:** Split large components into smaller chunks that can be loaded on demand. Use dynamic imports for loading components asynchronously.
|
||||
* **Library Splitting:** Extract commonly used libraries into separate chunks to allow browsers to cache them independently.
|
||||
|
||||
## 2. Common Patterns and Anti-Patterns
|
||||
|
||||
### 2.1. Design Patterns
|
||||
|
||||
* **Selectors:** Use selectors to abstract the state shape and compute derived data. Selectors improve performance by memoizing results and prevent components from re-rendering unnecessarily.
|
||||
* **Custom Hooks:** Create custom hooks for accessing Redux state and dispatching actions. This simplifies component logic and promotes code reuse. For example:
|
||||
|
||||
typescript
|
||||
import { useDispatch, useSelector } from 'react-redux';
|
||||
import { increment, decrement } from './counterSlice';
|
||||
import { RootState } from './store';
|
||||
|
||||
export const useCounter = () => {
|
||||
const count = useSelector((state: RootState) => state.counter.value);
|
||||
const dispatch = useDispatch();
|
||||
|
||||
const handleIncrement = () => {
|
||||
dispatch(increment());
|
||||
};
|
||||
|
||||
const handleDecrement = () => {
|
||||
dispatch(decrement());
|
||||
};
|
||||
|
||||
return { count, handleIncrement, handleDecrement };
|
||||
};
|
||||
|
||||
* **Redux Toolkit:** Utilize Redux Toolkit to simplify Redux setup and reduce boilerplate code. Redux Toolkit provides utilities for creating reducers, actions, and the store.
|
||||
|
||||
### 2.2. Recommended Approaches
|
||||
|
||||
* **Normalize State:** Structure your state as a normalized data structure, where each piece of data has a unique ID, and relationships between data are represented by IDs. This improves performance and simplifies data management. Use libraries like Normalizr to help with this.
|
||||
* **Immutability:** Treat your state as immutable and use immutable update patterns. This ensures predictable state transitions and prevents unexpected side effects.
|
||||
* **Middleware for Side Effects:** Use Redux middleware (e.g., Redux Thunk, Redux Saga) to handle asynchronous operations and side effects. Avoid performing side effects directly in reducers.
|
||||
|
||||
### 2.3. Anti-Patterns and Code Smells
|
||||
|
||||
* **Mutating State Directly:** Never mutate the state directly in reducers. Always create a new copy of the state with the desired changes.
|
||||
* **Performing Side Effects in Reducers:** Reducers should be pure functions and should not perform any side effects (e.g., API calls, logging).
|
||||
* **Storing UI State in Redux:** Avoid storing UI-specific state (e.g., component visibility, form input values) in the Redux store. Store UI state locally in component state.
|
||||
* **Over-reliance on Global State:** Avoid putting everything in the Redux store. Only store data that needs to be accessed by multiple components or across the entire application. Consider React Context or local component state for component-specific data.
|
||||
|
||||
### 2.4. State Management Best Practices
|
||||
|
||||
* **Minimize Global State:** Only store data in the Redux store that needs to be shared across multiple components. For component-specific state, use local component state.
|
||||
* **Use Selectors:** Use selectors to access and transform data from the Redux store. This allows you to abstract the state shape and prevent components from re-rendering unnecessarily.
|
||||
* **Immutable Updates:** Always update state immutably to ensure predictable state transitions and prevent unexpected side effects. Use libraries like Immer to simplify immutable updates.
|
||||
|
||||
### 2.5. Error Handling Patterns
|
||||
|
||||
* **Centralized Error Handling:** Implement a centralized error handling mechanism to catch and handle errors consistently throughout the application. Use error boundary components to catch errors in the UI.
|
||||
* **Action Creators for Errors:** Dispatch error actions to the Redux store when errors occur. This allows you to track errors and display error messages in the UI.
|
||||
* **Logging Errors:** Log errors to a central logging service for debugging and monitoring purposes.
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
### 3.1. Optimization Techniques
|
||||
|
||||
* **Memoization:** Use memoization techniques (e.g., `React.memo`, `useMemo`, Reselect) to prevent components from re-rendering unnecessarily.
|
||||
* **Batch Updates:** Batch multiple Redux dispatches into a single update to improve performance. Use `redux-batched-updates` or `unstable_batchedUpdates` from React DOM.
|
||||
* **Virtualization:** Use virtualization techniques (e.g., `react-window`, `react-virtualized`) to efficiently render large lists and tables.
|
||||
* **Code Splitting:** Split the application into smaller chunks to reduce the initial load time.
|
||||
|
||||
### 3.2. Memory Management
|
||||
|
||||
* **Avoid Memory Leaks:** Be mindful of memory leaks, especially in event listeners, timers, and subscriptions. Clean up resources properly when components unmount.
|
||||
* **Use WeakRefs:** Use WeakRefs to hold references to objects without preventing them from being garbage collected.
|
||||
* **Profile Memory Usage:** Use the browser's developer tools to profile memory usage and identify potential memory leaks.
|
||||
|
||||
### 3.3. Rendering Optimization
|
||||
|
||||
* **ShouldComponentUpdate / React.memo:** Use `shouldComponentUpdate` (for class components) or `React.memo` (for functional components) to prevent components from re-rendering unnecessarily.
|
||||
* **Pure Components:** Use pure components to automatically implement `shouldComponentUpdate` based on prop comparisons.
|
||||
* **Immutable Data Structures:** Use immutable data structures to make it easier to detect changes and prevent re-renders.
|
||||
|
||||
### 3.4. Bundle Size Optimization
|
||||
|
||||
* **Tree Shaking:** Use tree shaking to remove dead code from your bundles. Configure your bundler (e.g., Webpack, Parcel) to enable tree shaking.
|
||||
* **Code Splitting:** Split the application into smaller chunks to reduce the initial load time.
|
||||
* **Minification:** Minify your code to reduce the bundle size.
|
||||
* **Compression:** Compress your bundles using gzip or Brotli.
|
||||
|
||||
### 3.5. Lazy Loading Strategies
|
||||
|
||||
* **Route-Based Lazy Loading:** Load components only when their corresponding routes are visited.
|
||||
* **Component-Based Lazy Loading:** Load components on demand when they become visible in the UI.
|
||||
* **Image Lazy Loading:** Load images only when they scroll into view.
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
### 4.1. Common Vulnerabilities and Prevention
|
||||
|
||||
* **Cross-Site Scripting (XSS):** Prevent XSS vulnerabilities by sanitizing user input and escaping output.
|
||||
* **Cross-Site Request Forgery (CSRF):** Protect against CSRF attacks by using anti-CSRF tokens.
|
||||
* **Injection Attacks:** Prevent injection attacks (e.g., SQL injection, command injection) by validating user input and using parameterized queries.
|
||||
* **Authentication and Authorization:** Implement secure authentication and authorization mechanisms to protect sensitive data and resources.
|
||||
|
||||
### 4.2. Input Validation
|
||||
|
||||
* **Server-Side Validation:** Always validate user input on the server-side to prevent malicious data from being stored in the database.
|
||||
* **Client-Side Validation:** Use client-side validation to provide immediate feedback to users and reduce the load on the server.
|
||||
* **Whitelisting:** Use whitelisting to allow only specific characters or patterns in user input.
|
||||
|
||||
### 4.3. Authentication and Authorization Patterns
|
||||
|
||||
* **JSON Web Tokens (JWT):** Use JWTs for authentication and authorization. JWTs are stateless and can be easily verified on the server-side.
|
||||
* **OAuth 2.0:** Use OAuth 2.0 for delegated authorization. OAuth 2.0 allows users to grant third-party applications access to their resources without sharing their credentials.
|
||||
* **Role-Based Access Control (RBAC):** Implement RBAC to control access to resources based on user roles.
|
||||
|
||||
### 4.4. Data Protection Strategies
|
||||
|
||||
* **Encryption:** Encrypt sensitive data at rest and in transit.
|
||||
* **Data Masking:** Mask sensitive data to prevent unauthorized access.
|
||||
* **Data Anonymization:** Anonymize data to remove personally identifiable information (PII).
|
||||
|
||||
### 4.5. Secure API Communication
|
||||
|
||||
* **HTTPS:** Use HTTPS to encrypt communication between the client and the server.
|
||||
* **API Keys:** Use API keys to authenticate API requests.
|
||||
* **Rate Limiting:** Implement rate limiting to prevent abuse and denial-of-service attacks.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
### 5.1. Unit Testing Strategies
|
||||
|
||||
* **Test Reducers:** Test reducers to ensure that they handle actions correctly and update the state as expected.
|
||||
* **Test Selectors:** Test selectors to ensure that they return the correct data from the state.
|
||||
* **Test Actions:** Test action creators to ensure that they return the correct actions.
|
||||
* **Test Components:** Test components to ensure that they render correctly and handle user interactions as expected. Use tools like React Testing Library.
|
||||
|
||||
### 5.2. Integration Testing
|
||||
|
||||
* **Test Component Interactions:** Test how components interact with each other and with the Redux store.
|
||||
* **Test Data Flow:** Test the flow of data through the application, from the UI to the Redux store and back.
|
||||
* **Test API Integrations:** Test how the application integrates with external APIs.
|
||||
|
||||
### 5.3. End-to-End Testing
|
||||
|
||||
* **Test User Flows:** Test complete user flows to ensure that the application functions correctly from end to end. Use tools like Cypress or Playwright.
|
||||
* **Test Critical Functionality:** Test critical functionality (e.g., login, checkout) to ensure that it is working as expected.
|
||||
* **Test Accessibility:** Test the application for accessibility to ensure that it is usable by people with disabilities.
|
||||
|
||||
### 5.4. Test Organization
|
||||
|
||||
* **Test Folder Structure:** Organize tests in a way that mirrors the application's directory structure.
|
||||
* **Test Suites:** Group tests into logical suites based on functionality or component.
|
||||
* **Test Naming Conventions:** Use clear and consistent naming conventions for tests.
|
||||
|
||||
### 5.5. Mocking and Stubbing
|
||||
|
||||
* **Mock API Calls:** Mock API calls to isolate components and reducers during testing.
|
||||
* **Stub External Dependencies:** Stub external dependencies to control their behavior during testing.
|
||||
* **Use Mock Store:** Use a mock Redux store to test components that are connected to the store.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
### 6.1. Frequent Mistakes
|
||||
|
||||
* **Forgetting to Connect Components:** Forgetting to connect components to the Redux store, resulting in components not receiving state updates.
|
||||
* **Incorrectly Mapping State to Props:** Incorrectly mapping state to props, resulting in components not receiving the correct data.
|
||||
* **Not Updating State Immutably:** Not updating state immutably, leading to unexpected side effects and re-renders.
|
||||
* **Using `setState` with Redux:** Mixing `setState` with Redux can lead to inconsistencies and difficult-to-debug issues. Avoid using `setState` in components connected to Redux, unless for purely local, non-Redux-related state.
|
||||
|
||||
### 6.2. Edge Cases
|
||||
|
||||
* **Race Conditions:** Be aware of race conditions when handling asynchronous operations.
|
||||
* **Memory Leaks:** Watch out for memory leaks in event listeners, timers, and subscriptions.
|
||||
* **Performance Bottlenecks:** Identify and address performance bottlenecks, such as unnecessary re-renders or slow API calls.
|
||||
|
||||
### 6.3. Version-Specific Issues
|
||||
|
||||
* **Breaking Changes:** Be aware of breaking changes when upgrading React and Redux.
|
||||
* **Deprecated Features:** Avoid using deprecated features and migrate to the recommended alternatives.
|
||||
|
||||
### 6.4. Compatibility Concerns
|
||||
|
||||
* **Browser Compatibility:** Test the application in different browsers to ensure compatibility.
|
||||
* **Device Compatibility:** Test the application on different devices to ensure compatibility.
|
||||
|
||||
### 6.5. Debugging Strategies
|
||||
|
||||
* **Redux DevTools:** Use the Redux DevTools to inspect the Redux store, track actions, and time travel through state changes.
|
||||
* **Console Logging:** Use console logging to debug code and track the flow of data.
|
||||
* **Breakpoints:** Use breakpoints to pause execution and inspect variables in the debugger.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
### 7.1. Recommended Development Tools
|
||||
|
||||
* **Redux DevTools:** The Redux DevTools extension for Chrome and Firefox allows you to inspect the Redux store, track actions, and time travel through state changes.
|
||||
* **React Developer Tools:** The React Developer Tools extension for Chrome and Firefox allows you to inspect the React component tree and profile component performance.
|
||||
* **ESLint:** ESLint is a linter that helps you identify and fix code style issues and potential errors.
|
||||
* **Prettier:** Prettier is a code formatter that automatically formats your code to ensure consistency.
|
||||
|
||||
### 7.2. Build Configuration
|
||||
|
||||
* **Webpack:** Webpack is a module bundler that bundles your code and dependencies into optimized bundles for production.
|
||||
* **Parcel:** Parcel is a zero-configuration bundler that is easy to use and provides fast build times.
|
||||
* **Create React App:** Create React App is a tool that sets up a React development environment with sensible defaults.
|
||||
|
||||
### 7.3. Linting and Formatting
|
||||
|
||||
* **ESLint:** Use ESLint to enforce code style rules and prevent potential errors. Configure ESLint to use a popular style guide, such as Airbnb or Standard.
|
||||
* **Prettier:** Use Prettier to automatically format your code to ensure consistency. Integrate Prettier with ESLint to automatically fix code style issues.
|
||||
* **Husky and Lint-Staged:** Use Husky and Lint-Staged to automatically run linters and formatters on staged files before committing code.
|
||||
|
||||
### 7.4. Deployment Best Practices
|
||||
|
||||
* **Environment Variables:** Use environment variables to configure the application for different environments (e.g., development, staging, production).
|
||||
* **Continuous Integration:** Use a continuous integration (CI) system to automatically build and test the application whenever code is committed.
|
||||
* **Continuous Deployment:** Use a continuous deployment (CD) system to automatically deploy the application to production whenever a new release is created.
|
||||
* **Caching:** Configure caching on the server-side and client-side to improve performance.
|
||||
|
||||
### 7.5. CI/CD Integration
|
||||
|
||||
* **GitHub Actions:** Use GitHub Actions to automate the build, test, and deployment process.
|
||||
* **CircleCI:** Use CircleCI to automate the build, test, and deployment process.
|
||||
* **Jenkins:** Use Jenkins to automate the build, test, and deployment process.
|
||||
@@ -0,0 +1,167 @@
|
||||
---
|
||||
description: Enforces best practices for React development, covering code structure, performance, security, and testing to ensure maintainable and efficient applications.
|
||||
globs: **/*.{js,jsx,ts,tsx}
|
||||
---
|
||||
- **Use Functional Components with Hooks:**
|
||||
- Favor functional components over class components for simplicity and better performance.
|
||||
- Leverage React Hooks (useState, useEffect, useContext, useReducer, useCallback, useMemo, useRef, useImperativeHandle, useLayoutEffect, useDebugValue) for managing state, side effects, and context.
|
||||
|
||||
- **Component Composition:**
|
||||
- Build complex UIs by composing smaller, reusable components.
|
||||
- Use props to pass data down the component tree and callbacks to handle events.
|
||||
|
||||
- **Meaningful Component Names:**
|
||||
- Give component names that accurately reflect their functionality.
|
||||
- Follow a consistent naming convention (e.g., PascalCase for components, camelCase for props).
|
||||
|
||||
- **Keep Components Small and Focused:**
|
||||
- Adhere to the Single Responsibility Principle; each component should have a clear, focused purpose.
|
||||
- Break down large components into smaller, more manageable pieces.
|
||||
|
||||
- **Destructuring Props:**
|
||||
- Use destructuring to access props within functional components for improved readability.
|
||||
|
||||
- **Avoid Inline Styles:**
|
||||
- Use CSS modules, styled-components, or a CSS-in-JS library for managing styles instead of inline styles.
|
||||
- Keep styles separate from component logic for better maintainability.
|
||||
|
||||
- **Use Arrow Functions:**
|
||||
- Use arrow functions for concise syntax and lexical `this` binding.
|
||||
- Be mindful of performance implications when passing arrow functions directly as props; consider using `useCallback`.
|
||||
|
||||
- **PropTypes for Type Checking (with alternatives):**
|
||||
- Use PropTypes (though consider TypeScript) to define the expected types of props passed to components.
|
||||
- Enforce type checking at runtime to catch type-related errors early.
|
||||
- Strongly consider TypeScript for static type checking for enhanced code quality and maintainability.
|
||||
|
||||
- **Immutability:**
|
||||
- Treat state as immutable; avoid directly modifying state objects.
|
||||
- Use `setState`, the spread operator (`...`), or immutable data structures (e.g., Immutable.js) to update state.
|
||||
|
||||
- **Code Organization and Structure:**
|
||||
- **Directory Structure:**
|
||||
- Organize components into folders based on features or modules.
|
||||
- Use a `components` directory for reusable UI elements.
|
||||
- Consider a `hooks` directory for custom hooks.
|
||||
- Separate API services into a `services` or `api` directory.
|
||||
- **File Naming Conventions:**
|
||||
- Use `.jsx` or `.tsx` extensions for React components.
|
||||
- Name files according to the component they export (e.g., `MyComponent.jsx`).
|
||||
- Use `index.js` or `index.ts` files to export multiple components from a directory.
|
||||
- **Module Organization:**
|
||||
- Use ES modules (`import` and `export`) for modular code.
|
||||
- Group related components and logic into modules.
|
||||
- **Component Architecture:**
|
||||
- **Atomic Design:** Consider using Atomic Design principles (Atoms, Molecules, Organisms, Templates, Pages) to structure your components.
|
||||
- **Presentational and Container Components:** Separate presentational (UI-focused) and container (logic-focused) components.
|
||||
- **Code Splitting:**
|
||||
- Use React.lazy and Suspense to lazy-load components and reduce initial bundle size.
|
||||
- Implement route-based code splitting for larger applications.
|
||||
- Consider using dynamic imports for splitting non-route components as well.
|
||||
|
||||
- **Common Patterns and Anti-patterns:**
|
||||
- **Design Patterns:**
|
||||
- **Higher-Order Components (HOCs):** Use HOCs to share logic between components.
|
||||
- **Render Props:** Use render props for more flexible code reuse.
|
||||
- **Compound Components:** Create components that implicitly share state and behavior with their children (e.g., `<Tabs>`, `<Tab>`).
|
||||
- **Provider Pattern:** Use the Context API to provide data to a subtree of components.
|
||||
- **Recommended Approaches:**
|
||||
- Use controlled components for forms to manage input values in React state.
|
||||
- Use keys when rendering lists of elements for efficient updates.
|
||||
- Use memoization techniques (React.memo, useMemo, useCallback) to prevent unnecessary re-renders.
|
||||
- **Anti-patterns:**
|
||||
- **Direct DOM Manipulation:** Avoid directly manipulating the DOM; use React's virtual DOM instead.
|
||||
- **Mutating State Directly:** Never directly modify state; use `setState` or the appropriate hook update function.
|
||||
- **Over-reliance on Global State:** Avoid storing too much state in global stores; consider component-level state or context when appropriate.
|
||||
- **State Management:**
|
||||
- **Component State:** Use `useState` for simple component-level state.
|
||||
- **Context API:** Use the Context API for sharing state across a subtree of components.
|
||||
- **Redux/Zustand/Recoil/MobX:** Consider using a state management library (Redux, Zustand, Recoil, MobX) for complex application state.
|
||||
- **Error Handling:**
|
||||
- **Error Boundaries:** Use Error Boundaries to catch errors during rendering and prevent the entire application from crashing.
|
||||
- **Try/Catch Blocks:** Use try/catch blocks for handling errors in event handlers and lifecycle methods.
|
||||
|
||||
- **Performance Considerations:**
|
||||
- **Memoization:**
|
||||
- Use `React.memo` to memoize functional components and prevent unnecessary re-renders.
|
||||
- Use `useMemo` to memoize computed values and prevent unnecessary recalculations.
|
||||
- Use `useCallback` to memoize event handler functions and prevent unnecessary re-renders of child components.
|
||||
- **Virtualization:**
|
||||
- Use virtualization libraries (e.g., `react-window`, `react-virtualized`) for rendering large lists of data efficiently.
|
||||
- **Debouncing and Throttling:**
|
||||
- Use debouncing and throttling techniques to limit the frequency of function calls in response to user input.
|
||||
- **Image Optimization:**
|
||||
- Optimize images for the web to reduce file sizes and improve loading times.
|
||||
- Use lazy loading for images that are not immediately visible.
|
||||
- **Bundle Size Optimization:**
|
||||
- Use code splitting to reduce the initial bundle size.
|
||||
- Remove unused code with tree shaking.
|
||||
- Compress code with minification.
|
||||
- **Rendering Optimization:**
|
||||
- Use `shouldComponentUpdate` (in class components) or `React.memo` (in functional components) to prevent unnecessary re-renders.
|
||||
- Implement pure components (components that only re-render when their props change) for performance gains.
|
||||
- **Lazy Loading:**
|
||||
- Use `React.lazy` and `Suspense` to load components on demand and improve initial load time.
|
||||
|
||||
- **Security Best Practices:**
|
||||
- **XSS Prevention:**
|
||||
- Sanitize user input to prevent cross-site scripting (XSS) attacks.
|
||||
- Use React's built-in escaping mechanisms to render data safely.
|
||||
- **CSRF Protection:**
|
||||
- Implement cross-site request forgery (CSRF) protection to prevent unauthorized requests.
|
||||
- Use anti-CSRF tokens to verify requests.
|
||||
- **Authentication and Authorization:**
|
||||
- Use secure authentication and authorization patterns to protect sensitive data and functionality.
|
||||
- Implement strong password policies.
|
||||
- Use multi-factor authentication.
|
||||
- **Data Protection:**
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use HTTPS to secure communication between the client and server.
|
||||
- **Secure API Communication:**
|
||||
- Validate API responses to prevent unexpected data from compromising the application.
|
||||
|
||||
- **Testing Approaches:**
|
||||
- **Unit Testing:**
|
||||
- Write unit tests to verify the behavior of individual components and functions.
|
||||
- Use testing libraries like Jest and React Testing Library.
|
||||
- **Integration Testing:**
|
||||
- Write integration tests to verify the interaction between multiple components and modules.
|
||||
- **End-to-End Testing:**
|
||||
- Write end-to-end tests to verify the entire application flow.
|
||||
- Use testing frameworks like Cypress or Playwright.
|
||||
- **Test Organization:**
|
||||
- Organize tests into a `__tests__` directory alongside the component files.
|
||||
- Follow a consistent naming convention for test files (e.g., `MyComponent.test.jsx`).
|
||||
- **Mocking and Stubbing:**
|
||||
- Use mocking and stubbing techniques to isolate components during testing.
|
||||
- Mock external dependencies like API calls and browser APIs.
|
||||
|
||||
- **Common Pitfalls and Gotchas:**
|
||||
- **Incorrect `this` Binding:**
|
||||
- Be mindful of `this` binding in class components; use arrow functions or `bind` to ensure the correct context.
|
||||
- **Missing Keys in Lists:**
|
||||
- Provide unique keys to elements when rendering lists to prevent rendering issues.
|
||||
- **Asynchronous State Updates:**
|
||||
- Understand how `setState` and hook update functions handle asynchronous updates; use functional updates when necessary.
|
||||
- **Memory Leaks:**
|
||||
- Clean up side effects in `useEffect` hooks to prevent memory leaks.
|
||||
- **Version-Specific Issues:**
|
||||
- Be aware of compatibility concerns when upgrading React versions.
|
||||
- Consult the React documentation and release notes for migration guides.
|
||||
|
||||
- **Tooling and Environment:**
|
||||
- **Recommended Development Tools:**
|
||||
- VS Code with React-specific extensions (e.g., ESLint, Prettier, Babel).
|
||||
- Chrome DevTools for debugging.
|
||||
- React Developer Tools extension for inspecting component hierarchy and state.
|
||||
- **Build Configuration:**
|
||||
- Use tools like webpack, Parcel, or Rollup for bundling and optimizing code.
|
||||
- Configure Babel to transpile JSX and modern JavaScript syntax.
|
||||
- **Linting and Formatting:**
|
||||
- Use ESLint with React-specific rules to enforce code style and best practices.
|
||||
- Use Prettier to automatically format code.
|
||||
- **Deployment Best Practices:**
|
||||
- Use a CDN to serve static assets.
|
||||
- Use server-side rendering (SSR) or static site generation (SSG) for improved performance and SEO.
|
||||
- **CI/CD Integration:**
|
||||
- Integrate CI/CD pipelines for automated testing, building, and deployment.
|
||||
Reference in New Issue
Block a user