---
description: Definitive guidelines for writing idiomatic, maintainable, and performant React applications using modern best practices and TypeScript.
globs: **/*.{jsx,tsx}
---
# react Best Practices
This guide outlines the non-negotiable standards for building React applications within our team. Adherence ensures predictable behavior, simplifies debugging, and enables future optimizations.
## 1. Core React Principles: Purity & Rules of Hooks
Components and Hooks **must be pure**. They should always return the same output given the same inputs (props, state, context) and not cause side effects during rendering. Obey the [Rules of Hooks](https://react.dev/reference/rules/rules-of-hooks) without exception.
### ❌ BAD: Impure component / Side effect in render
```tsx
function ProductList({ products }) {
// ❌ Modifies external data during render
products.sort((a, b) => a.name.localeCompare(b.name));
return (/* ... */);
}
function MyComponent() {
// ❌ Hook called conditionally
if (Math.random() > 0.5) {
const [count, setCount] = useState(0);
}
return (/* ... */);
}
```
### ✅ GOOD: Pure component / Correct Hook usage
```tsx
import { useMemo, useState } from 'react';
function ProductList({ products }) {
// ✅ Sort data immutably or memoize if expensive
const sortedProducts = useMemo(() =>
[...products].sort((a, b) => a.name.localeCompare(b.name)),
[products]
);
return (/* ... */);
}
function MyComponent() {
// ✅ Hooks always at the top level
const [count, setCount] = useState(0);
// ... conditional logic after hooks
return (/* ... */);
}
```
## 2. Code Organization & Naming
Organize code by **feature** using the `bulletproof-react` pattern. Use TypeScript (`.tsx`) for all components.
* **One Component Per File**: Except for small, pure, stateless components closely related to a parent.
* **Naming**:
* Components: `PascalCase` (e.g., `UserProfile.tsx`)
* Custom Hooks: `use` prefix + `PascalCase` (e.g., `useAuth.ts`)
* Functions/Variables: `camelCase`
* CSS Classes: `kebab-case` (via CSS Modules or utility classes)
### ✅ GOOD: Feature-based structure
```
src/
├── features/
│ ├── auth/
│ │ ├── components/
│ │ │ ├── LoginForm.tsx
│ │ │ └── AuthButton.tsx
│ │ ├── hooks/
│ │ │ └── useAuth.ts
│ │ └── api/auth.ts
│ └── products/
│ ├── components/
│ │ ├── ProductCard.tsx
│ │ └── ProductList.tsx
│ └── hooks/useProducts.ts
├── components/ui/ // Reusable, generic UI components
│ ├── Button.tsx
│ └── Modal.tsx
└── App.tsx
```
## 3. Component Design & Patterns
Prioritize **function components with Hooks**. Separate concerns into "smart" (data/logic) and "dumb" (presentational) components.
### ❌ BAD: Class components / Mixed concerns
```tsx
// ❌ Class component (avoid)
class UserProfile extends React.Component { /* ... */ }
// ❌ Component fetches data AND renders complex UI
function ProductPage() {
const [products, setProducts] = useState([]);
useEffect(() => { /* fetch products */ }, []);
return (/* complex product list UI */);
}
```
### ✅ GOOD: Function components / Separation of concerns
```tsx
// ✅ Use function components with hooks
function UserProfile({ user }) { /* ... */ }
// ✅ Smart component (container) handles data fetching
function ProductListContainer() {
const { products, isLoading } = useProducts(); // Custom hook for data
if (isLoading) return
Count: {count}, Computed: {computedValue}
> ); } // Child component that receives the memoized callback const Child = React.memo(({ onClick }: { onClick: () => void }) => { console.log('Rendering Child'); return ; }); ``` ## 6. Common Pitfalls * **Never mutate props or state directly.** Always create new objects/arrays. * **Never call component functions directly.** Use JSX. * **Ensure `useEffect` cleanup functions are always provided** for subscriptions or timers. * **Correct `useEffect` dependency arrays** are critical to avoid infinite loops or stale closures. ### ❌ BAD: Direct mutation / Calling component as function ```tsx function MyComponent({ items }) { // ❌ Mutating props directly items.push('new item'); const [data, setData] = useState({ value: 1 }); // ❌ Mutating state directly data.value = 2; setData(data); // ❌ Calling component as a function return MyOtherComponent(); } ``` ### ✅ GOOD: Immutable updates / JSX usage ```tsx function MyComponent({ items }) { const [data, setData] = useState({ value: 1 }); // ✅ Create a new array for updates const updatedItems = [...items, 'new item']; // ✅ Create a new object for state updates setData(prevData => ({ ...prevData, value: 2 })); // ✅ Use JSX for components return