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:
sanjeed5
2025-02-27 16:58:58 +05:30
parent 676f3376bf
commit 5068ef1d22
88 changed files with 20037 additions and 0 deletions
@@ -0,0 +1,207 @@
---
description: This rule enforces best practices and coding standards for Chakra UI projects, including accessibility, styling, performance, and security. It aims to provide clear, actionable guidance for developers using Chakra UI.
globs: **/*.{js,jsx,ts,tsx}
---
- **Accessibility**: Ensure all components follow WAI-ARIA standards, including keyboard navigation and screen reader support.
- Use semantic HTML elements where appropriate (e.g., `<button>`, `<input>`, `<nav>`).
- Provide alternative text for images using the `alt` prop on the `<Image>` component.
- Ensure sufficient color contrast between text and background colors. Use a tool like [WebAIM's Color Contrast Checker](https://webaim.org/resources/contrastchecker/) to verify.
- Use the `aria-label`, `aria-labelledby`, and `aria-describedby` props to provide descriptive information to assistive technologies.
- Test your components with a screen reader (e.g., NVDA, VoiceOver) to ensure they are accessible.
- **Prop-Based Styling**: Use style props instead of CSS classes for faster and more intuitive styling.
- Leverage Chakra UI's extensive set of style props for common CSS properties (e.g., `m`, `p`, `bg`, `color`, `fontSize`, `fontWeight`).
- Use the `sx` prop for more advanced styling that goes beyond the available style props. However, prefer style props where applicable for consistency.
- Apply responsive styles using array or object syntax for different breakpoints.
- **Centralized Theming**: Manage colors, sizes, and styles in one place for consistency across the application.
- Extend the default Chakra UI theme using the `extendTheme` function to customize colors, fonts, sizes, and component styles.
- Use semantic tokens for theme values (e.g., `colors.brand.primary`, `sizes.spacing.md`) instead of hardcoding values directly in your components.
- Use the `useTheme` hook to access theme values within your components.
- Organize your theme file to ensure easy modifications and readability
- **Modular Components**: Build complex UIs by combining small, reusable components like `Box`, `Flex`, and `Stack`.
- Follow atomic design principles to structure your components into atoms, molecules, and organisms.
- Create custom components that encapsulate specific UI patterns and logic.
- Use composition to build more complex components from simpler ones.
- Use the `forwardRef` API when building components that need to directly access a DOM node.
- **Responsive Design**: Use array syntax for responsive styles and leverage hooks like `useBreakpointValue` for adaptive layouts.
- Use the array syntax to define different values for different breakpoints (e.g., `fontSize={['sm', 'md', 'lg']}`).
- Use the object syntax for more explicit breakpoint control (e.g., `templateColumns={{ base: '1fr', md: 'repeat(2, 1fr)' }}`).
- Use the `useBreakpointValue` hook to dynamically adjust layouts based on the current breakpoint.
- Utilize `useMediaQuery` hook for conditional rendering of components or sections.
- **Simplicity and Composition**: Keep component APIs simple and break them down into smaller parts to maintain flexibility.
- Design components with a minimal set of props to keep their APIs clean and easy to use.
- Use composition to allow consumers to customize the appearance and behavior of your components.
- Avoid creating monolithic components with too many responsibilities.
- **Custom Theme Creation**: Extend the default theme to match design requirements and ensure consistent styling.
- Use `extendTheme` to customize the default Chakra UI theme and create consistent styling.
- Define custom color palettes, typography, spacing, and breakpoints.
- Override component styles to match your design system.
- **Testing and Documentation**: Document components and their usage, and ensure thorough testing for accessibility and functionality.
- Write unit tests for your components using Jest and React Testing Library.
- Test for accessibility using `axe-core` and `jest-axe`.
- Document your components with clear and concise JSDoc comments.
- Use a tool like Storybook to create a living style guide for your components.
- Use Typescript to ensure you have strongly typed components.
- **Code Organization and Structure:**
- **Directory Structure Best Practices:**
- Structure your project based on features or components.
- Common structure: `src/components`, `src/pages`, `src/utils`, `src/theme`, `src/hooks`.
- Place related components, hooks, and styles in the same directory.
- **File Naming Conventions:**
- Use PascalCase for component file names (e.g., `Button.tsx`).
- Use camelCase for hook file names (e.g., `useDisclosure.ts`).
- Use descriptive names for utility functions (e.g., `formatDate.ts`).
- **Module Organization:**
- Group related components and functions into modules.
- Use `index.ts` files to re-export members from a module.
- Avoid circular dependencies between modules.
- **Component Architecture:**
- Use a component-based architecture with reusable components.
- Separate presentational components from container components.
- Prefer functional components with hooks over class components.
- **Code Splitting Strategies:**
- Use dynamic imports to load components and modules on demand.
- Split your application into routes or feature modules.
- Use React.lazy and Suspense for code splitting at the component level.
- **Common Patterns and Anti-patterns:**
- **Design Patterns Specific to Chakra UI:**
- **Compound Components:** Create components like `Tabs` and `Accordion` where child components share state and logic.
- **Control Props:** Use props like `value` and `onChange` for controlled components, enabling external state management.
- **Render Props:** Provide a render prop to allow consumers to customize the rendering of a component.
- **Recommended Approaches for Common Tasks:**
- Use Chakra UI's layout components (`Box`, `Flex`, `Grid`, `Stack`) for structuring your UI.
- Use the `useDisclosure` hook for managing the state of modals, drawers, and other toggleable components.
- Use the `useColorMode` hook for implementing dark mode support.
- **Anti-patterns and Code Smells to Avoid:**
- Avoid using inline styles directly; prefer style props or the `sx` prop.
- Avoid mutating the Chakra UI theme directly; always use `extendTheme` to create a new theme.
- Avoid tightly coupling components to specific data sources; make them more generic and reusable.
- **State Management Best Practices:**
- Use local component state for simple UI state.
- Use context for sharing state between components that are not directly related.
- Use a state management library like Redux or Zustand for more complex application state.
- **Error Handling Patterns:**
- Use try-catch blocks to handle errors gracefully.
- Display user-friendly error messages to the user.
- Log errors to a monitoring service for debugging.
- Implement fallback components to handle unexpected errors during rendering.
- **Performance Considerations:**
- **Optimization Techniques:**
- Use `React.memo` to memoize functional components and prevent unnecessary re-renders.
- Use `useCallback` and `useMemo` to memoize functions and values that are used as props to child components.
- Avoid creating new objects or functions in render methods.
- **Memory Management:**
- Clean up event listeners and timers in `useEffect` hooks.
- Avoid storing large amounts of data in component state.
- Use weak references to prevent memory leaks.
- **Rendering Optimization:**
- Use virtualization libraries like `react-window` or `react-virtualized` to render large lists efficiently.
- Optimize expensive calculations and data transformations.
- Use the `shouldComponentUpdate` lifecycle method or `React.PureComponent` to prevent unnecessary re-renders in class components (avoid when using hooks).
- **Bundle Size Optimization:**
- Use tree shaking to remove unused code from your bundles.
- Use code splitting to load only the code that is needed for a particular page or feature.
- Use image optimization techniques to reduce the size of your images.
- **Lazy Loading Strategies:**
- Use `React.lazy` and `Suspense` for lazy loading components.
- Use intersection observers to lazy load images and other assets that are not initially visible.
- **Security Best Practices:**
- **Common Vulnerabilities and How to Prevent Them:**
- **Cross-Site Scripting (XSS):** Sanitize user input to prevent the execution of malicious scripts.
- **Cross-Site Request Forgery (CSRF):** Use CSRF tokens to protect against unauthorized requests.
- **SQL Injection:** Use parameterized queries or an ORM to prevent SQL injection attacks.
- **Input Validation:**
- Validate all user input on both the client and server sides.
- Use regular expressions or validation libraries to enforce data formats.
- Escape or encode user input before displaying it in the UI.
- **Authentication and Authorization Patterns:**
- Use a secure authentication protocol like OAuth 2.0 or OpenID Connect.
- Store passwords securely using a hashing algorithm like bcrypt.
- Implement role-based access control (RBAC) to restrict access to sensitive data and functionality.
- **Data Protection Strategies:**
- Encrypt sensitive data at rest and in transit.
- Use HTTPS to secure communication between the client and server.
- Protect API keys and other secrets by storing them in environment variables.
- **Secure API Communication:**
- Use HTTPS for all API requests.
- Validate API responses to ensure they are in the expected format.
- Implement rate limiting to prevent abuse of your APIs.
- **Testing Approaches:**
- **Unit Testing Strategies:**
- Write unit tests for individual components and functions.
- Test for different input values and edge cases.
- Use mocking and stubbing to isolate components from external dependencies.
- **Integration Testing:**
- Write integration tests to verify the interaction between components.
- Test the flow of data between components.
- Test the integration with external APIs and services.
- **End-to-End Testing:**
- Write end-to-end tests to simulate user interactions and verify the overall functionality of the application.
- Use a testing framework like Cypress or Puppeteer.
- Test for accessibility and performance.
- **Test Organization:**
- Organize your tests into separate directories for unit tests, integration tests, and end-to-end tests.
- Use descriptive names for your test files and test cases.
- Follow a consistent testing style.
- **Mocking and Stubbing:**
- Use mocking to replace external dependencies with mock objects that simulate their behavior.
- Use stubbing to replace specific methods or properties of a dependency with predefined values.
- Use a mocking library like Jest's `jest.mock` or `sinon.js`.
- **Common Pitfalls and Gotchas:**
- **Frequent Mistakes Developers Make:**
- Not following accessibility guidelines.
- Overusing inline styles.
- Mutating the Chakra UI theme directly.
- Not testing components thoroughly.
- Not optimizing performance.
- **Edge Cases to Be Aware Of:**
- Handling different screen sizes and orientations.
- Handling different input methods (keyboard, mouse, touch).
- Handling different locales and languages.
- Handling different network conditions.
- **Version-Specific Issues:**
- Be aware of breaking changes between Chakra UI versions.
- Read the release notes carefully when upgrading.
- Test your application thoroughly after upgrading.
- **Compatibility Concerns:**
- Ensure your application is compatible with different browsers and devices.
- Use a tool like BrowserStack or Sauce Labs to test your application on different environments.
- **Debugging Strategies:**
- Use the browser's developer tools to inspect the DOM and debug your JavaScript code.
- Use a debugger like VS Code's built-in debugger.
- Use logging statements to track the flow of data and execution.
- **Tooling and Environment:**
- **Recommended Development Tools:**
- VS Code with the ESLint, Prettier, and TypeScript extensions.
- Chrome Developer Tools or Firefox Developer Tools.
- React Developer Tools browser extension.
- **Build Configuration:**
- Use a build tool like Webpack, Parcel, or Rollup.
- Configure your build tool to optimize your bundles and perform tree shaking.
- Use environment variables to configure your application for different environments.
- **Linting and Formatting:**
- Use ESLint with a configuration like eslint-config-react-app to enforce code style and best practices.
- Use Prettier to format your code automatically.
- Configure your editor to automatically lint and format your code on save.
- **Deployment Best Practices:**
- Use a continuous integration and continuous deployment (CI/CD) pipeline to automate your deployments.
- Deploy your application to a hosting provider like Netlify, Vercel, or AWS.
- Use a content delivery network (CDN) to cache your static assets.
- **CI/CD Integration:**
- Integrate your CI/CD pipeline with your testing and linting tools.
- Automate the process of building, testing, and deploying your application.
- Use a CI/CD platform like GitHub Actions, CircleCI, or Travis CI.
@@ -0,0 +1,273 @@
---
description: Comprehensive guide to best practices when developing with Material-UI/MUI, covering code organization, performance, security, testing, and common pitfalls. It focuses on creating maintainable, scalable, and performant React applications using MUI components.
globs: **/*.{js,jsx,ts,tsx}
---
# Material-UI/MUI Best Practices and Coding Standards
This document outlines best practices and coding standards for developing React applications using Material-UI (MUI). Following these guidelines will help you create maintainable, scalable, performant, and secure applications.
## 1. Code Organization and Structure
### 1.1 Directory Structure Best Practices
Adopt a clear and consistent directory structure to improve code maintainability and collaboration. A common approach is to organize code by feature or domain.
src/
components/
[ComponentName]/
[ComponentName].jsx # Component implementation
[ComponentName].module.css # Component-specific styles (CSS Modules)
[ComponentName].test.jsx # Unit tests
index.js # (Optional) Export the component
pages/
[PageName]/
[PageName].jsx # Page component
index.js # (Optional) Export the page component
styles/
theme.js # MUI theme configuration
global.css # Global styles
utils/
api.js # API client
helpers.js # Utility functions
App.jsx # Main application component
index.jsx # Entry point
### 1.2 File Naming Conventions
- **Components:** Use PascalCase for component file names (e.g., `MyButton.jsx`).
- **Styles:** Use camelCase or kebab-case for style file names (e.g., `myButton.module.css` or `my-button.module.css`). Prefer CSS modules.
- **Utilities:** Use camelCase for utility file names (e.g., `api.js`, `helpers.js`).
- **Tests:** Use the `.test.jsx` or `.spec.jsx` suffix for test files (e.g., `MyComponent.test.jsx`).
- **Indexes**: `index.js` should export the main entity contained within its parent folder.
### 1.3 Module Organization
- **Component-Specific Modules:** Encapsulate styles, logic, and tests within a component's directory to promote modularity and reusability.
- **Theme Module:** Centralize MUI theme customization in a dedicated module (`theme.js`).
- **Utility Modules:** Group related utility functions into separate modules (e.g., `api.js` for API calls, `helpers.js` for data manipulation). Import selectively only the parts you need from larger modules.
### 1.4 Component Architecture
- **Presentational and Container Components:** Separate concerns by creating presentational (UI-focused) and container (data-fetching and state management) components. Consider using hooks for simpler components.
- **Composition over Inheritance:** Favor component composition over inheritance to create flexible and reusable UI elements.
- **Controlled Components:** Use controlled components with explicit state management for better control and predictability.
- **Small Components:** Create smaller, focused components that do one thing well. This promotes reuse and testability.
### 1.5 Code Splitting Strategies
- **Route-Based Splitting:** Use React.lazy and Suspense to split your application into smaller chunks that are loaded on demand based on the current route.
- **Component-Based Splitting:** Lazy-load less critical components to reduce the initial bundle size. Useful for complex dialogs, or infrequently used features.
- **Library Splitting:** If certain libraries are used only in specific parts of your application, consider splitting them into separate chunks.
## 2. Common Patterns and Anti-patterns
### 2.1 Design Patterns Specific to Material-UI/MUI
- **Theming:** Use the `ThemeProvider` to customize the MUI theme globally. Define your color palette, typography, and other theme values in `theme.js`. Use `createTheme` function to extend the default theme.
- **Styling with `sx` prop:** Employ the `sx` prop for simple, one-off style customizations.
- **Styling with `styled` API:** Use the `styled` API for creating reusable, theme-aware components. This is the recommended approach for component styling in MUI v5 and above.
- **Grid System:** Leverage the `Grid` component for creating responsive layouts.
- **Hooks**: Use React hooks extensively for state management and side effects. MUI components work seamlessly with hooks.
### 2.2 Recommended Approaches for Common Tasks
- **Form Handling:** Use `TextField` components with proper validation and state management libraries like Formik or React Hook Form.
- **Data Display:** Use `Table`, `List`, and `Card` components to display data in a structured and visually appealing manner.
- **Navigation:** Use `AppBar`, `Drawer`, and `BottomNavigation` components for application navigation.
- **Notifications:** Implement notifications using the `Snackbar` component.
- **Dialogs/Modals**: Use the `Dialog` component to display modal content.
### 2.3 Anti-patterns and Code Smells to Avoid
- **Inline Styles:** Avoid inline styles as they are difficult to maintain and do not support theming. Use the `sx` prop or `styled` API instead. While the `sx` prop is quick, prefer `styled` components for reusability.
- **Direct DOM Manipulation:** Avoid directly manipulating the DOM. Use React's state management and component lifecycle methods to update the UI.
- **Over-nesting Components:** Avoid deeply nested component structures as they can impact performance and readability. Refactor into smaller, more focused components.
- **Mutating Theme Directly**: Don't directly mutate the theme object. Use `createTheme` and `ThemeProvider` to apply changes.
- **Ignoring Accessibility:** Ensure your components are accessible by providing proper ARIA attributes and keyboard navigation support.
### 2.4 State Management Best Practices
- **Local Component State:** Use `useState` and `useReducer` for managing component-specific state.
- **Global Application State:** Use Context API, Redux, Zustand, or Jotai for managing global application state.
- **Lifting State Up:** Lift state up to the nearest common ancestor component when multiple components need to share state.
- **Immutable Data:** Treat state as immutable and use immutable data structures to prevent unexpected side effects. Libraries like Immer can help.
### 2.5 Error Handling Patterns
- **Error Boundaries:** Use error boundaries to catch JavaScript errors in components and prevent the entire application from crashing.
- **Centralized Error Handling:** Implement a centralized error handling mechanism to log errors and display user-friendly error messages.
- **Try-Catch Blocks:** Use try-catch blocks to handle potential errors in asynchronous operations or API calls.
- **Defensive Programming**: Validate props, check for null/undefined values, and handle potential edge cases.
## 3. Performance Considerations
### 3.1 Optimization Techniques
- **Memoization:** Use `React.memo` to memoize functional components and prevent unnecessary re-renders. Use `useMemo` and `useCallback` hooks to memoize expensive computations and function references.
- **Virtualization:** Use virtualization libraries like `react-window` or `react-virtualized` to efficiently render large lists or tables.
- **Debouncing and Throttling:** Use debouncing and throttling to limit the frequency of expensive operations like API calls or event handlers.
- **Code Splitting:** Implement code splitting to reduce the initial bundle size and improve load times.
- **Image Optimization:** Optimize images by compressing them and using appropriate formats (e.g., WebP). Use lazy loading for images below the fold.
- **CDN**: Host static assets on a CDN.
### 3.2 Memory Management
- **Avoid Memory Leaks:** Be mindful of memory leaks, especially in event listeners and subscriptions. Clean up resources in the `useEffect` hook's cleanup function.
- **Garbage Collection:** Understand how JavaScript's garbage collection works and avoid creating unnecessary objects or closures that can lead to memory leaks.
### 3.3 Rendering Optimization
- **ShouldComponentUpdate (Class Components):** Implement `shouldComponentUpdate` (or `React.memo` in functional components) to prevent unnecessary re-renders when the props or state have not changed.
- **PureComponent (Class Components):** Extend `PureComponent` for components that rely solely on props for rendering, as it provides a shallow prop comparison.
- **Key Prop:** Always provide a unique `key` prop when rendering lists of components. This helps React efficiently update the DOM.
- **Minimize DOM Updates:** Reduce the number of DOM updates by batching state updates and using techniques like requestAnimationFrame.
### 3.4 Bundle Size Optimization
- **Tree Shaking:** Ensure your build process supports tree shaking to remove unused code from your bundle.
- **Minification:** Minify your code to reduce the bundle size.
- **Compression:** Use gzip or Brotli compression to reduce the size of your assets during transmission.
- **Dependency Analysis:** Analyze your dependencies to identify and remove unnecessary libraries.
### 3.5 Lazy Loading Strategies
- **React.lazy and Suspense:** Use `React.lazy` and `Suspense` to lazy load components and improve initial load times.
- **Intersection Observer API:** Use the Intersection Observer API to lazy load components when they become visible in the viewport.
## 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 libraries like DOMPurify to sanitize HTML.
- **Cross-Site Request Forgery (CSRF):** Implement CSRF protection by using anti-CSRF tokens.
- **SQL Injection:** Use parameterized queries or ORMs to prevent SQL injection attacks.
- **Authentication and Authorization Issues:** Implement secure authentication and authorization mechanisms to protect sensitive data and resources.
- **Denial of Service (DoS):** Implement rate limiting and other security measures to prevent DoS attacks.
### 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 your database.
- **Sanitization:** Sanitize user input to remove or encode potentially harmful characters or code.
### 4.3 Authentication and Authorization Patterns
- **JSON Web Tokens (JWT):** Use JWTs for authentication and authorization.
- **OAuth 2.0:** Use OAuth 2.0 for delegating authorization to third-party applications.
- **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 protect it from unauthorized access.
- **Data Minimization:** Collect only the necessary data to minimize the risk of data breaches.
### 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 of your API.
- **Input Validation**: Perform extensive input validation on API endpoints.
## 5. Testing Approaches
### 5.1 Unit Testing Strategies
- **Test Driven Development (TDD):** Consider using TDD to write tests before implementing the code.
- **Component Testing:** Unit test individual components in isolation to ensure they function correctly.
- **Mocking Dependencies:** Mock external dependencies like API calls or third-party libraries to isolate the component under test.
- **Test Coverage:** Aim for high test coverage to ensure that most of your code is tested.
### 5.2 Integration Testing
- **Test Component Interactions:** Integration tests verify the interactions between different components.
- **Test Data Flow:** Test the flow of data between components to ensure that data is passed correctly.
- **Mock API Endpoints:** Mock API endpoints to simulate real-world scenarios.
### 5.3 End-to-End Testing
- **Simulate User Interactions:** End-to-end tests simulate user interactions to verify that the application functions correctly from the user's perspective.
- **Test Critical User Flows:** Focus on testing critical user flows like login, registration, and checkout.
- **Use Testing Frameworks:** Use testing frameworks like Cypress or Playwright to automate end-to-end tests.
### 5.4 Test Organization
- **Colocate Tests with Components:** Place test files in the same directory as the component they test.
- **Use Descriptive Test Names:** Use descriptive test names to clearly indicate what the test is verifying.
- **Organize Tests by Feature:** Organize tests by feature to improve maintainability.
### 5.5 Mocking and Stubbing
- **Mock API Calls:** Mock API calls to isolate components during testing.
- **Stub External Dependencies:** Stub external dependencies to control their behavior during testing.
- **Use Mocking Libraries:** Use mocking libraries like Jest or Sinon to create mocks and stubs.
## 6. Common Pitfalls and Gotchas
### 6.1 Frequent Mistakes Developers Make
- **Not Using the ThemeProvider:** Neglecting to use the `ThemeProvider` for consistent styling.
- **Overriding Styles Incorrectly:** Incorrectly overriding MUI component styles (e.g., using CSS specificity issues).
- **Ignoring Responsiveness:** Failing to design responsive layouts using the `Grid` component.
- **Not Using the Latest Version:** Using older versions of MUI that may have known bugs or security vulnerabilities.
- **Over-reliance on `any` type in Typescript**: Not defining accurate types can lead to runtime errors.
### 6.2 Edge Cases to Be Aware Of
- **Server-Side Rendering (SSR):** MUI requires special configuration for SSR to prevent CSS hydration issues.
- **Accessibility (a11y):** Ensure components are accessible by providing proper ARIA attributes and keyboard navigation support.
- **Browser Compatibility:** Test your application in different browsers to ensure compatibility.
- **Internationalization (i18n):** Consider internationalization when designing your application.
### 6.3 Version-Specific Issues
- **Breaking Changes:** Be aware of breaking changes when upgrading MUI versions. Refer to the migration guide for each version.
- **Deprecated Features:** Avoid using deprecated features as they may be removed in future versions.
### 6.4 Compatibility Concerns
- **React Version:** Ensure that your MUI version is compatible with your React version.
- **Third-Party Libraries:** Be aware of compatibility issues between MUI and other third-party libraries.
### 6.5 Debugging Strategies
- **Use Browser Developer Tools:** Use browser developer tools to inspect the DOM, debug JavaScript code, and profile performance.
- **Use React Developer Tools:** Use the React Developer Tools to inspect the component tree, view component props and state, and profile performance.
- **Use Logging Statements:** Use logging statements to trace the execution of your code and identify potential issues.
- **Use a Debugger:** Use a debugger to step through your code and inspect variables.
## 7. Tooling and Environment
### 7.1 Recommended Development Tools
- **IDE:** Visual Studio Code (VS Code) with extensions like ESLint, Prettier, and React Developer Tools.
- **Package Manager:** npm, yarn, or pnpm.
- **Build Tool:** Webpack, Parcel, or Rollup.
- **Testing Framework:** Jest or Mocha.
- **Linting and Formatting:** ESLint and Prettier.
### 7.2 Build Configuration
- **Webpack Configuration:** Configure Webpack to optimize your bundle size, enable code splitting, and handle assets.
- **Babel Configuration:** Configure Babel to transpile your code to older versions of JavaScript for browser compatibility.
### 7.3 Linting and Formatting
- **ESLint:** Configure ESLint to enforce code style and prevent common errors. Use a shared ESLint configuration like Airbnb or Standard.
- **Prettier:** Configure Prettier to automatically format your code.
- **Husky and Lint-Staged:** Use Husky and Lint-Staged to run linters and formatters before committing code.
### 7.4 Deployment Best Practices
- **Choose a Hosting Provider:** Choose a reliable hosting provider like Netlify, Vercel, or AWS.
- **Configure Environment Variables:** Configure environment variables for different environments (e.g., development, staging, production).
- **Optimize Assets:** Optimize assets like images and fonts before deploying your application.
- **Use a CDN:** Use a CDN to serve static assets.
### 7.5 CI/CD Integration
- **Choose a CI/CD Tool:** Choose a CI/CD tool like GitHub Actions, Jenkins, or CircleCI.
- **Automate Tests:** Automate tests to run automatically on every commit or pull request.
- **Automate Deployment:** Automate deployment to automatically deploy your application to different environments.
@@ -0,0 +1,192 @@
---
description: This rule provides comprehensive best practices for developing with Shadcn UI, covering code organization, performance, security, and testing.
globs: **/*.{js,jsx,ts,tsx}
---
# Shadcn UI Best Practices
This document outlines best practices for developing with Shadcn UI, covering code organization, common patterns, performance considerations, security, testing, common pitfalls, and tooling.
## 1. Code Organization and Structure
- **Directory Structure:**
- Organize components into logical directories based on functionality or domain. For example, place form-related components in a `components/forms` directory.
- Separate components into their own files. Each component should have a dedicated file named after the component (e.g., `Button.tsx`).
- Consider using an `index.ts` file within each directory to export all components from that directory, simplifying imports.
- Structure directories to reflect the UI hierarchy. For example, `/components/layout` for layout related components and `/components/ui` for reusable UI elements.
- **File Naming Conventions:**
- Use PascalCase for component file names (e.g., `MyComponent.tsx`).
- Use camelCase for variable and function names (e.g., `handleClick`).
- Use descriptive names that clearly indicate the purpose of the component or function.
- **Module Organization:**
- Break down complex components into smaller, reusable modules.
- Keep components focused on a single responsibility.
- Utilize shared utility functions and constants to avoid code duplication. Create a `utils` directory for helper functions.
- Use `components` directory to store UI components.
- **Component Architecture:**
- Favor composition over inheritance. Create flexible components that can be customized through props.
- Design components with clear separation of concerns: presentational components (UI) and container components (logic).
- Use functional components with hooks for managing state and side effects.
- **Code Splitting Strategies:**
- Implement lazy loading for non-critical components to improve initial load time.
- Utilize React.lazy and Suspense for code splitting at the component level.
- Configure your bundler (e.g., Webpack, Parcel) to automatically split code into smaller chunks.
- Consider route-based code splitting for larger applications.
## 2. Common Patterns and Anti-patterns
- **Design Patterns Specific to Shadcn UI:**
- Leverage the existing components provided by Shadcn UI whenever possible.
- Customize components using styling solutions like Tailwind CSS's utility classes or CSS variables.
- Create compound components by combining existing Shadcn UI components to build more complex UI elements.
- **Recommended Approaches for Common Tasks:**
- Use Shadcn UI's form components (e.g., `Input`, `Select`) for handling user input.
- Implement accessible components by following ARIA guidelines and using appropriate HTML semantics.
- Use the `cn` utility (classnames library) provided by Shadcn UI to manage CSS class names effectively.
- **Anti-patterns and Code Smells to Avoid:**
- Directly modifying the Shadcn UI component code.
- Overusing custom CSS, as Shadcn UI is built with Tailwind CSS.
- Neglecting accessibility considerations.
- Creating overly complex components with too many responsibilities.
- **State Management Best Practices:**
- Use React's built-in `useState` hook for simple component-level state.
- Consider using a state management library like Zustand, Redux, or Recoil for more complex application state.
- Avoid mutating state directly; always use the setState function or a state management library's update methods.
- **Error Handling Patterns:**
- Implement error boundaries to catch errors in components and prevent the entire application from crashing.
- Use try-catch blocks to handle errors in asynchronous operations and API calls.
- Provide informative error messages to users.
- Log errors to a monitoring service for debugging and analysis.
## 3. Performance Considerations
- **Optimization Techniques:**
- Minimize re-renders by using `React.memo` for functional components and `shouldComponentUpdate` for class components.
- Optimize event handlers by using useCallback to prevent unnecessary re-creation of functions.
- Debounce or throttle expensive operations to reduce the frequency of execution.
- **Memory Management:**
- Avoid memory leaks by properly cleaning up event listeners and timers in the `useEffect` hook.
- Release unused resources, such as large data structures, when they are no longer needed.
- **Rendering Optimization:**
- Use virtualized lists or grids for rendering large datasets.
- Batch DOM updates to minimize reflows and repaints.
- Use CSS containment to isolate rendering changes to specific parts of the DOM.
- **Bundle Size Optimization:**
- Remove unused code and dependencies using tree shaking.
- Minify JavaScript and CSS files to reduce their size.
- Compress images using tools like ImageOptim or TinyPNG.
- **Lazy Loading Strategies:**
- Implement lazy loading for images and other media assets.
- Use the Intersection Observer API to detect when elements are visible in the viewport and load them on demand.
## 4. Security Best Practices
- **Common Vulnerabilities and How to Prevent Them:**
- Prevent cross-site scripting (XSS) attacks by sanitizing user input and escaping HTML entities.
- Protect against cross-site request forgery (CSRF) attacks by using anti-CSRF tokens.
- Avoid storing sensitive information, such as API keys or passwords, in client-side code.
- **Input Validation:**
- Validate user input on both the client-side and server-side.
- Use a validation library like Zod or Yup to define data schemas and enforce validation rules.
- Sanitize user input to remove potentially harmful characters or code.
- **Authentication and Authorization Patterns:**
- Use a secure authentication protocol, such as OAuth 2.0 or OpenID Connect.
- Implement role-based access control (RBAC) to restrict access to sensitive resources.
- Store user credentials securely using hashing and salting.
- **Data Protection Strategies:**
- Encrypt sensitive data at rest and in transit.
- Use HTTPS to protect data transmitted between the client and server.
- Implement data masking to hide sensitive information from unauthorized users.
- **Secure API Communication:**
- Use HTTPS for all API requests.
- Implement rate limiting to prevent abuse and denial-of-service attacks.
- Validate API responses to ensure data integrity.
## 5. Testing Approaches
- **Unit Testing Strategies:**
- Write unit tests for individual components and functions.
- Use a testing framework like Jest or Mocha.
- Test component behavior with different props and inputs.
- **Integration Testing:**
- Write integration tests to verify that components work together correctly.
- Test the interaction between components and APIs.
- **End-to-End Testing:**
- Write end-to-end tests to simulate user interactions and verify that the application functions as expected.
- Use a testing framework like Cypress or Playwright.
- **Test Organization:**
- Organize tests into separate files based on the component or feature being tested.
- Use descriptive test names that clearly indicate the purpose of the test.
- **Mocking and Stubbing:**
- Use mocking and stubbing to isolate components and functions during testing.
- Mock external dependencies, such as APIs or third-party libraries.
## 6. Common Pitfalls and Gotchas
- **Frequent Mistakes Developers Make:**
- Forgetting to handle edge cases.
- Overcomplicating components.
- Neglecting accessibility.
- Ignoring performance considerations.
- **Edge Cases to Be Aware Of:**
- Handling different screen sizes and devices.
- Dealing with slow network connections.
- Handling invalid or unexpected user input.
- **Version-Specific Issues:**
- Be aware of breaking changes between Shadcn UI versions.
- Consult the Shadcn UI changelog for migration instructions.
- **Compatibility Concerns:**
- Ensure that your application is compatible with the target browsers and devices.
- Test your application on different browsers and devices.
- **Debugging Strategies:**
- Use browser developer tools to inspect the DOM and debug JavaScript code.
- Use console logging to track the flow of execution and identify errors.
- Use a debugger to step through code and inspect variables.
## 7. Tooling and Environment
- **Recommended Development Tools:**
- Visual Studio Code (VS Code) with extensions for React, TypeScript, and Tailwind CSS.
- A browser with developer tools (e.g., Chrome DevTools, Firefox Developer Tools).
- A terminal for running commands and scripts.
- **Build Configuration:**
- Use a build tool like Webpack, Parcel, or Rollup to bundle your application.
- Configure your build tool to optimize code for production.
- **Linting and Formatting:**
- Use ESLint to enforce code style and identify potential errors.
- Use Prettier to automatically format code.
- Configure your editor to automatically lint and format code on save.
- **Deployment Best Practices:**
- Deploy your application to a reliable hosting provider.
- Use a content delivery network (CDN) to serve static assets.
- Configure your server to serve compressed files.
- **CI/CD Integration:**
- Use a continuous integration and continuous deployment (CI/CD) pipeline to automate the build, test, and deployment process.
- Integrate your CI/CD pipeline with your version control system.
@@ -0,0 +1,92 @@
---
description: Provides guidelines and best practices for effectively using Tailwind CSS, focusing on performance, organization, and maintainability. This rule ensures consistent styling and efficient component development across the project.
globs: **/*.{html,js,jsx,ts,tsx,vue,svelte}
---
- **Leverage Tailwind's PurgeCSS:** Configure PurgeCSS properly to remove unused styles in production, drastically reducing the final CSS bundle size. Ensure you configure it to scan all relevant files (HTML, JS/TS components, etc.).
- Configure `tailwind.config.js` with the appropriate `content` array to ensure that PurgeCSS correctly identifies used classes.
- Use the JIT (Just-In-Time) compiler in development for faster build times and complete feature availability.
- **Use Tailwind's Configuration File:** Customize Tailwind's default theme, colors, spacing, and breakpoints in the `tailwind.config.js` file. This ensures consistency across the project and allows for easy updates.
- Define a design system using semantic names for colors and spacing (e.g., `primary-brand`, `space-md`) rather than hardcoding values.
- Utilize Tailwind's theme extension feature to add custom styles without overriding the defaults.
- **Adopt a Mobile-First Approach:** Design components and layouts starting with mobile devices and then progressively enhance them for larger screens using Tailwind's responsive modifiers (e.g., `sm:`, `md:`, `lg:`, `xl:`).
- Avoid deeply nested responsive modifiers. Refactor components to be more adaptable if necessary.
- **Utilize Tailwind UI (if applicable):** If using Tailwind UI, leverage the pre-built components as a starting point and customize them to fit your project's specific needs. Be aware of licensing implications.
- Extract common patterns and modifications into reusable components to avoid repeating code.
- **Optimize for Performance:** Beyond PurgeCSS, be mindful of CSS specificity and avoid overly complex selectors. Use Tailwind's `apply` directive judiciously.
- Use `@layer` directive in your CSS to organize your styles and improve performance.
- Consider CSS extraction and inlining critical CSS for faster initial page load.
- Profile your application's CSS to identify performance bottlenecks.
- **Stay Organized with Components:** Break down complex UIs into smaller, reusable components. Use a consistent naming convention for component files and Tailwind classes.
- Create a component library to store and manage reusable components.
- Use tools like Storybook or Styleguidist to document and showcase components.
- Follow the principles of atomic design when structuring your components.
- **Integrate with a Design System:** Define a clear design system with consistent typography, colors, and spacing. Use Tailwind's configuration file to enforce these standards.
- Document the design system and make it accessible to all team members.
- Use design tokens to manage and update design values across the project.
- **Code Organization and Structure:**
- **Directory Structure:** Organize components into logical directories based on functionality or page sections (e.g., `components/`, `pages/`, `layouts/`).
- **File Naming Conventions:** Use descriptive and consistent file names for components (e.g., `Button.jsx`, `Card.vue`).
- **Module Organization:** Group related components and utilities into modules.
- **Component Architecture:** Favor composition over inheritance when building components. Use functional components and hooks where appropriate.
- **Code Splitting:** Implement code splitting to reduce initial load time. Use dynamic imports to load components on demand.
- **Common Patterns and Anti-patterns:**
- **Design Patterns:** Use the composite pattern for building complex UIs from smaller components. Use the provider pattern for managing global state.
- **Recommended Approaches:** Use Tailwind's utility classes for styling elements. Create custom components for complex or reusable styles.
- **Anti-patterns:** Avoid using inline styles or `!important` declarations. Avoid overly specific CSS selectors.
- **State Management:** Use a state management library (e.g., Redux, Zustand, Vuex) for complex state management. Use React Context or Vue provide/inject for simpler state management.
- **Error Handling:** Implement error boundaries to catch errors in components. Display user-friendly error messages.
- **Performance Considerations:**
- **Optimization Techniques:** Minimize the number of DOM updates. Use memoization to prevent unnecessary re-renders.
- **Memory Management:** Avoid memory leaks by properly cleaning up event listeners and subscriptions.
- **Rendering Optimization:** Use virtualization for rendering large lists. Use the `shouldComponentUpdate` lifecycle method or `React.memo` to prevent unnecessary re-renders.
- **Bundle Size Optimization:** Use code splitting and tree shaking to reduce bundle size. Compress images and other assets.
- **Lazy Loading:** Lazy load images and other resources that are not immediately visible on the page.
- **Security Best Practices:**
- **Common Vulnerabilities:** Be aware of XSS vulnerabilities when rendering user-generated content. Sanitize inputs to prevent XSS attacks.
- **Input Validation:** Validate all user inputs to prevent unexpected behavior.
- **Authentication and Authorization:** Implement secure authentication and authorization mechanisms.
- **Data Protection:** Protect sensitive data by encrypting it both in transit and at rest.
- **Secure API Communication:** Use HTTPS for all API communication. Validate API responses.
- **Testing Approaches:**
- **Unit Testing:** Write unit tests for individual components and functions.
- **Integration Testing:** Write integration tests to ensure that components work together correctly.
- **End-to-End Testing:** Write end-to-end tests to test the entire application flow.
- **Test Organization:** Organize tests into logical directories based on functionality.
- **Mocking and Stubbing:** Use mocking and stubbing to isolate components during testing.
- **Common Pitfalls and Gotchas:**
- **Frequent Mistakes:** Forgetting to configure PurgeCSS. Overusing the `apply` directive. Not using a consistent naming convention.
- **Edge Cases:** Handling different screen sizes and devices. Dealing with browser compatibility issues.
- **Version-Specific Issues:** Be aware of breaking changes in new Tailwind CSS versions.
- **Compatibility Concerns:** Ensure that Tailwind CSS is compatible with your target browsers.
- **Debugging Strategies:** Use browser developer tools to inspect CSS and debug styling issues.
- **Tooling and Environment:**
- **Recommended Development Tools:** Use a code editor with Tailwind CSS IntelliSense. Use a browser with developer tools.
- **Build Configuration:** Configure your build tool (e.g., webpack, Parcel, Vite) to process Tailwind CSS.
- **Linting and Formatting:** Use ESLint and Prettier to enforce code style and prevent errors. Configure a Tailwind CSS plugin for your linter.
- **Deployment Best Practices:** Use a CDN to serve static assets. Configure caching to improve performance.
- **CI/CD Integration:** Integrate Tailwind CSS into your CI/CD pipeline to automate testing and deployment.
- **Naming Conventions:**
- Use BEM (Block, Element, Modifier) or a similar naming convention for custom CSS classes. This helps to maintain consistency and avoid naming conflicts.
- **Accessibility (A11y):**
- Use semantic HTML elements to improve accessibility. Provide alternative text for images. Ensure that your website is navigable using a keyboard.
- **Consider using `theme()` helper function:** When using Javascript to dynamically set tailwind values, you can use the `theme()` helper function from tailwindcss to get theme values for custom classes. This ensures they are based on values you have specified in your `tailwind.config.js` and can be purged properly.
- **Custom Utilities vs Components:** When creating custom styling, decide when to make a utility versus a component. Utilities are best for single purpose styling like font-weight, or color changes. Components should be used for more complex combinations of styling, that require more html structure.
- **Beware of arbitrary values and `!important`:** Using these excessively will reduce your maintainability and reusability of components and CSS.