Files
main/rules-mdc/react.mdc
T
sanjeed5 5cbc31aee9 Update generation system with modern prompts and Gemini 2.5 Flash
- Upgrade to gemini-2.5-flash model for better output quality
- Add date context to prompts (December 2025) for current best practices
- Implement Exa cache system to avoid redundant API calls
- Add --refresh-exa flag to bypass cache when needed
- Restructure prompts with date at end for Gemini prompt caching
- Enhance system prompt to emphasize modern patterns
- Switch from JSON mode to direct MDC format generation
- Add loguru dependency for better logging
- Remove requirements.txt in favor of uv
2025-12-17 21:12:15 +05:30

146 lines
9.1 KiB
Plaintext

---
description: Provides comprehensive best practices for writing clean, performant, and maintainable React applications, covering code organization, common patterns, performance, state management, and accessibility.
globs: **/*.{jsx,tsx}
---
# React Best Practices
This guide outlines best practices for developing robust, scalable, and maintainable React applications. Adhering to these principles will lead to more predictable code, easier debugging, and improved collaboration.
## 1. Code Organization and Structure
* **One Component Per File:** Generally, each React component should reside in its own file. For very small, stateless, or pure components that are tightly coupled, multiple components can be in one file.
* **Naming:** Use `PascalCase` for component files (e.g., `Button.jsx`, `UserProfile.tsx`) and `camelCase` for variables and functions.
* **Functional Components & Hooks:** Prefer functional components and React Hooks (`useState`, `useEffect`, `useContext`, `useReducer`, custom hooks) over class components for new development.
* **Sensible Folder Structure:**
* Start with a flat `src/` and evolve as the project grows.
* Common structure:
```
src/
├── assets/ # Images, icons, fonts
├── components/ # Reusable UI components (e.g., Button, Modal)
├── features/ # Domain-specific features (e.g., Auth, Products, UserProfile)
├── hooks/ # Custom React Hooks
├── pages/ # Top-level page components (e.g., HomePage, DashboardPage)
├── api/ # API service calls
├── utils/ # Utility functions (e.g., formatters, validators)
├── types/ # TypeScript type definitions
├── routes/ # Application routing configuration
├── store/ # Global state management (if applicable)
└── App.jsx
```
* **CSS Modules:** Use CSS Modules (`*.module.css`) or styled-components for encapsulated styling to prevent style conflicts.
* **Colocate Tests:** Place unit tests (`*.test.js` or `*.spec.js`) alongside the component files they test.
## 2. Common Patterns and Anti-patterns
### Patterns
* **Custom Hooks:** Extract reusable stateful logic into custom hooks.
```jsx
// hooks/useToggle.js
import { useState, useCallback } from 'react';
const useToggle = (initialValue = false) => {
const [value, setValue] = useState(initialValue);
const toggle = useCallback(() => setValue(prev => !prev), []);
return [value, toggle];
};
// Usage: const [isOpen, toggleOpen] = useToggle(false);
```
* **Compound Components:** For complex UI patterns where components work together (e.g., `Select.Root`, `Select.Option`).
* **Context API:** Use for sharing "global" data (e.g., theme, user info) across the component tree without prop drilling.
### Anti-patterns
* **Prop Drilling:** Avoid passing props through many layers of components that don't directly use them. Use Context API or state management libraries instead.
* **Direct DOM Manipulation:** Let React manage the DOM. Use `useRef` sparingly for direct DOM access (e.g., focusing an input).
* **Mutating State Directly:** Never directly modify state objects or arrays. Always create a new copy.
```jsx
// BAD
// state.items.push(newItem);
// setState(state);
// GOOD
setItems(prevItems => [...prevItems, newItem]);
```
* **Complex Logic in `useEffect`:** Keep `useEffect` focused on a single side effect. Extract complex logic into separate functions or custom hooks.
## 3. Performance Considerations
* **`React.memo`, `useMemo`, `useCallback`:**
* `React.memo`: Memoizes functional components to prevent re-renders if props haven't changed. Use for "pure" components with expensive render logic.
* `useMemo`: Memoizes expensive calculations.
* `useCallback`: Memoizes functions to prevent unnecessary re-creation, useful for passing stable functions to `React.memo` children or `useEffect` dependencies.
* **Caution:** Don't over-optimize. These add overhead; use them when profiling indicates a performance bottleneck.
* **Key Prop in Lists:** Always provide a unique and stable `key` prop when rendering lists of elements. Avoid using array indexes as keys if the list items can change order, be added, or removed.
```jsx
{items.map(item => (
<ListItem key={item.id} item={item} />
))}
```
* **Lazy Loading / Code Splitting:** Use `React.lazy` and `Suspense` to split your application's code into smaller chunks, loading them only when needed.
```jsx
const LazyComponent = React.lazy(() => import('./MyHeavyComponent'));
function App() {
return (
<React.Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</React.Suspense>
);
}
```
* **Virtualization:** For very long lists, use libraries like `react-window` or `react-virtualized` to render only the visible items.
## 4. Common Pitfalls and Gotchas
* **Incorrect `useEffect` Dependencies:**
* Missing dependencies can lead to stale closures or incorrect behavior.
* Over-specifying dependencies can lead to infinite loops or unnecessary re-runs.
* Use ESLint's `exhaustive-deps` rule.
* **Mutable Objects in State:** Modifying an object or array directly in state won't trigger a re-render because React performs a shallow comparison. Always create new objects/arrays.
* **Race Conditions in `useEffect`:** Handle asynchronous operations in `useEffect` with cleanup functions to prevent updates on unmounted components or outdated data.
```jsx
useEffect(() => {
let didCancel = false;
async function fetchData() {
const data = await myApiCall();
if (!didCancel) {
setData(data);
}
}
fetchData();
return () => { didCancel = true; }; // Cleanup
}, [someDependency]);
```
* **Props are Read-Only:** Never modify props directly within a component. If a value needs to change, it should be managed as state in the component itself or its parent.
## 5. Component Architecture
* **Single Responsibility Principle:** Each component should ideally do one thing well. This makes components easier to understand, test, and reuse.
* **Presentational vs. Container Components (Smart/Dumb):**
* **Presentational (Dumb) Components:** Focus on *how things look*. Receive data and callbacks via props, have no state of their own (or only UI state), and are typically stateless functional components.
* **Container (Smart) Components:** Focus on *how things work*. Manage state, fetch data, and pass data/callbacks to presentational components.
* **Composition Over Inheritance:** React encourages composition. Build complex UIs by composing smaller, simpler components together.
## 6. State Management
* **Local Component State (`useState`):** For state that is only relevant to a single component.
* **`useReducer`:** A good alternative to `useState` for more complex state logic, especially when state transitions depend on previous state or involve multiple sub-values.
* **Context API:** For sharing state or functions that are needed by many components at different nesting levels, avoiding prop drilling.
* **External Libraries (Redux, Zustand, Jotai, Recoil):** Consider these for large applications with complex global state requirements, cross-cutting concerns, or when you need advanced features like middleware, time-travel debugging, or derived state.
## 7. Accessibility (A11y)
* **Semantic HTML:** Use appropriate HTML elements (`<button>`, `<input>`, `<nav>`, `<main>`, etc.) for their intended purpose.
* **ARIA Attributes:** Use `aria-*` attributes when semantic HTML isn't sufficient for custom interactive components (e.g., `aria-label`, `aria-expanded`).
* **Keyboard Navigation:** Ensure all interactive elements are reachable and operable via keyboard (Tab, Enter, Space).
* **Focus Management:** Manage focus for dynamic content like modals, dropdowns, and form submissions.
* **Alt Text for Images:** Provide meaningful `alt` attributes for all `<img>` tags.
* **ESLint `jsx-a11y` Plugin:** Integrate this plugin into your development workflow to catch common accessibility issues early.
## 8. Testing Approaches
* **Unit Testing:** Focus on testing individual components or pure functions in isolation.
* **React Testing Library:** Preferred for testing React components. It encourages testing components the way users interact with them, focusing on behavior rather than implementation details.
* **Jest:** A popular JavaScript testing framework often used with React Testing Library.
* **Integration Testing:** Test how multiple components work together.
* **End-to-End (E2E) Testing:** Test the entire application flow from a user's perspective using tools like Cypress or Playwright.
* **Mocking:** Mock API calls and external dependencies to ensure tests are fast, reliable, and isolated.
* **Test Alongside Components:** Keep test files (`*.test.js` or `*.spec.js`) in the same directory as the components they test for easy discoverability.