mirror of
https://github.com/sanjeed5/awesome-cursor-rules-mdc.git
synced 2026-11-27 21:22:55 +08:00
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
196 lines
12 KiB
Plaintext
196 lines
12 KiB
Plaintext
---
|
|
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. |