---
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 => (
))}
```
* **Lazy Loading / Code Splitting:** Use `React.lazy` and `Suspense` to split your application's code into smaller chunks, loading them only when needed.
```jsx
const LazyComponent = React.lazy(() => import('./MyHeavyComponent'));
function App() {
return (
Loading...}>
);
}
```
* **Virtualization:** For very long lists, use libraries like `react-window` or `react-virtualized` to render only the visible items.
## 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 (`