> ## Documentation Index
> Fetch the complete documentation index at: https://docs.weventures.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# React

> Comprehensive learning guide for React development

## What is React?

<Tabs>
  <Tab title="For Beginners">
    React is a **JavaScript library** for building user interfaces, created by Facebook (now Meta). Think of it as a way to build interactive websites using reusable pieces called "components."

    **Key Concepts:**

    * **Components**: Building blocks of your UI (like LEGO pieces)
    * **State**: Data that can change over time (like a counter value)
    * **Props**: Data passed from parent to child components (like function arguments)
    * **JSX**: HTML-like syntax inside JavaScript

    **Why React?**

    * Build once, reuse everywhere (components)
    * Automatically updates UI when data changes
    * Huge ecosystem and community
    * Used by Facebook, Instagram, Netflix, Airbnb, and thousands more

    **The Mental Model:**

    ```
    Data Changes → React Updates UI Automatically
    ```

    Instead of manually manipulating the DOM, you describe what the UI should look like, and React handles the updates.
  </Tab>

  <Tab title="How We Use It">
    React is the foundation of all our frontend applications. We use it with Next.js for full-stack apps and Vite for client-side applications. Our React code follows modern patterns with TypeScript, hooks, and functional components.
  </Tab>
</Tabs>

## Essential React Concepts

### 1. Components

<Tabs>
  <Tab title="Function Components">
    ```tsx theme={null}
    // Modern React uses function components
    function Welcome({ name }: { name: string }) {
      return <h1>Hello, {name}!</h1>
    }

    // With TypeScript interface
    interface UserProps {
      name: string
      age: number
      isActive?: boolean
    }

    function UserCard({ name, age, isActive = false }: UserProps) {
      return (
        <div className="card">
          <h2>{name}</h2>
          <p>Age: {age}</p>
          {isActive && <span>🟢 Active</span>}
        </div>
      )
    }
    ```
  </Tab>

  <Tab title="Class Components (Legacy)">
    ```tsx theme={null}
    // Old pattern - avoid in new code
    class Welcome extends React.Component<{ name: string }> {
      render() {
        return <h1>Hello, {this.props.name}!</h1>
      }
    }
    ```
  </Tab>
</Tabs>

### 2. State Management

<CodeGroup>
  ```tsx useState Hook theme={null}
  import { useState } from 'react'

  function Counter() {
    const [count, setCount] = useState(0)

    return (
      <div>
        <p>Count: {count}</p>
        <button onClick={() => setCount(count + 1)}>
          Increment
        </button>
        <button onClick={() => setCount(prev => prev - 1)}>
          Decrement (using updater function)
        </button>
      </div>
    )
  }
  ```

  ```tsx Complex State theme={null}
  interface User {
    name: string
    email: string
    preferences: {
      theme: 'light' | 'dark'
      notifications: boolean
    }
  }

  function UserProfile() {
    const [user, setUser] = useState<User>({
      name: '',
      email: '',
      preferences: {
        theme: 'light',
        notifications: true
      }
    })

    const updateTheme = (theme: 'light' | 'dark') => {
      setUser(prev => ({
        ...prev,
        preferences: {
          ...prev.preferences,
          theme
        }
      }))
    }

    return <div>{/* UI */}</div>
  }
  ```
</CodeGroup>

### 3. Effects & Side Effects

```tsx theme={null}
import { useEffect, useState } from 'react'

function DataFetcher() {
  const [data, setData] = useState(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)

  useEffect(() => {
    // Runs after component mounts
    fetch('/api/data')
      .then(res => res.json())
      .then(setData)
      .catch(setError)
      .finally(() => setLoading(false))

    // Cleanup function (runs on unmount)
    return () => {
      console.log('Component unmounting')
    }
  }, []) // Empty array = run once on mount

  if (loading) return <div>Loading...</div>
  if (error) return <div>Error: {error.message}</div>
  return <div>{JSON.stringify(data)}</div>
}
```

### 4. Props & Prop Drilling

```tsx theme={null}
// Parent component
function App() {
  const [user, setUser] = useState({ name: 'John', role: 'admin' })

  return <Dashboard user={user} />
}

// Child component
function Dashboard({ user }: { user: User }) {
  return <Sidebar user={user} />
}

// Grandchild component
function Sidebar({ user }: { user: User }) {
  return <UserMenu user={user} />
}

// This is "prop drilling" - passing props through many levels
// Solution: Use Context API or state management library
```

### 5. Context API (Avoid Prop Drilling)

```tsx theme={null}
import { createContext, useContext, useState } from 'react'

// Create context
const UserContext = createContext<User | null>(null)

// Provider component
function App() {
  const [user, setUser] = useState<User>({ name: 'John' })

  return (
    <UserContext.Provider value={user}>
      <Dashboard />
    </UserContext.Provider>
  )
}

// Consume context anywhere in the tree
function UserMenu() {
  const user = useContext(UserContext)
  return <div>{user?.name}</div>
}

// Custom hook pattern (recommended)
function useUser() {
  const context = useContext(UserContext)
  if (!context) throw new Error('useUser must be used within UserProvider')
  return context
}
```

## 100 Essential React Terms

<AccordionGroup>
  <Accordion title="Core Concepts (1-20)">
    1. **Component** - Reusable UI building block
    2. **JSX** - JavaScript XML syntax
    3. **Props** - Data passed to components
    4. **State** - Component's internal data
    5. **Virtual DOM** - In-memory representation of UI
    6. **Reconciliation** - Process of updating the DOM
    7. **Rendering** - Converting components to UI
    8. **Re-rendering** - Updating UI when data changes
    9. **Mount** - Component added to DOM
    10. **Unmount** - Component removed from DOM
    11. **Lifecycle** - Stages of component existence
    12. **Key** - Unique identifier for list items
    13. **Ref** - Reference to DOM element
    14. **Fragment** - Group elements without wrapper
    15. **Children** - Components/elements inside component
    16. **Composition** - Building complex UIs from simple components
    17. **Pure Component** - Component with no side effects
    18. **Controlled Component** - Form input controlled by React state
    19. **Uncontrolled Component** - Form input managed by DOM
    20. **Synthetic Event** - React's cross-browser event wrapper
  </Accordion>

  <Accordion title="Hooks (21-40)">
    21. **useState** - State management hook
    22. **useEffect** - Side effects hook
    23. **useContext** - Context consumption hook
    24. **useReducer** - Complex state management
    25. **useCallback** - Memoize functions
    26. **useMemo** - Memoize computed values
    27. **useRef** - Persist values across renders
    28. **useLayoutEffect** - Synchronous useEffect
    29. **useImperativeHandle** - Customize ref exposure
    30. **useDebugValue** - Debug custom hooks
    31. **useTransition** - Non-blocking updates (React 18)
    32. **useDeferredValue** - Defer expensive updates
    33. **useId** - Generate unique IDs
    34. **useSyncExternalStore** - Subscribe to external stores
    35. **useInsertionEffect** - CSS-in-JS libraries
    36. **Custom Hook** - Reusable stateful logic
    37. **Hook Rules** - Rules of Hooks (top-level only, etc.)
    38. **Dependency Array** - useEffect/useCallback dependencies
    39. **Stale Closure** - Outdated values in closures
    40. **Hook Flow** - Order of hook execution
  </Accordion>

  <Accordion title="Advanced Patterns (41-60)">
    41. **Higher-Order Component (HOC)** - Function that wraps components
    42. **Render Props** - Share code using props
    43. **Compound Components** - Components that work together
    44. **Controlled Props** - Props that control state
    45. **State Reducer Pattern** - Inversion of control for state
    46. **Provider Pattern** - Context provider pattern
    47. **Container/Presentational** - Logic/UI separation
    48. **Lifting State Up** - Move state to common ancestor
    49. **Prop Drilling** - Passing props through many levels
    50. **Code Splitting** - Load code on demand
    51. **Lazy Loading** - Defer component loading
    52. **Suspense** - Handle async operations
    53. **Error Boundary** - Catch React errors
    54. **Portal** - Render outside parent DOM
    55. **Forwarding Refs** - Pass refs to child components
    56. **Memoization** - Cache expensive computations
    57. **Batching** - Group state updates
    58. **Concurrent Rendering** - Interruptible rendering
    59. **Automatic Batching** - Batch updates everywhere (React 18)
    60. **Transitions** - Mark updates as non-urgent
  </Accordion>

  <Accordion title="Performance (61-75)">
    61. **React.memo** - Prevent unnecessary re-renders
    62. **shouldComponentUpdate** - Lifecycle optimization (legacy)
    63. **PureComponent** - Shallow prop comparison (legacy)
    64. **Profiler** - Measure render performance
    65. **Windowing** - Render only visible items
    66. **Debouncing** - Delay function execution
    67. **Throttling** - Limit function calls
    68. **Virtualization** - Render large lists efficiently
    69. **Web Workers** - Offload heavy computations
    70. **Bundle Size** - JavaScript file size
    71. **Tree Shaking** - Remove unused code
    72. **Code Splitting** - Split into chunks
    73. **Prefetching** - Load resources early
    74. **Hydration** - Attach React to SSR HTML
    75. **Streaming SSR** - Progressive rendering
  </Accordion>

  <Accordion title="State Management (76-85)">
    76. **Local State** - Component-specific state
    77. **Global State** - Application-wide state
    78. **Server State** - Data from API
    79. **URL State** - State in URL params
    80. **Redux** - Predictable state container
    81. **Zustand** - Lightweight state management
    82. **Jotai** - Atomic state management
    83. **Recoil** - Facebook's state library
    84. **MobX** - Observable state
    85. **XState** - State machines
  </Accordion>

  <Accordion title="Next.js Specifics (86-100)">
    86. **Server Component** - Runs on server (Next.js)
    87. **Client Component** - Runs in browser
    88. **Server Actions** - Server-side functions
    89. **App Router** - File-based routing (Next.js 13+)
    90. **Pages Router** - Legacy routing (Next.js)
    91. **Layout** - Shared UI across routes
    92. **Loading.tsx** - Loading states
    93. **Error.tsx** - Error handling
    94. **Route Handlers** - API routes
    95. **Middleware** - Request interception
    96. **Static Generation (SSG)** - Pre-render at build
    97. **Server-Side Rendering (SSR)** - Pre-render per request
    98. **Incremental Static Regeneration (ISR)** - Update static pages
    99. **Dynamic Routes** - \[param] based routes
    100. **Parallel Routes** - Multiple pages at once
  </Accordion>
</AccordionGroup>

## Common Libraries & Tools

<CardGroup cols={2}>
  <Card title="Data Fetching" icon="database">
    * **TanStack Query** (React Query) - Server state management
    * **SWR** - Stale-while-revalidate
    * **Axios** - HTTP client
    * **GraphQL** - Query language
    * **tRPC** - Type-safe APIs
  </Card>

  <Card title="State Management" icon="box">
    * **Zustand** - Lightweight, our go-to
    * **Redux Toolkit** - Redux simplified
    * **Jotai** - Atomic state
    * **Context API** - Built-in React
  </Card>

  <Card title="Forms" icon="input-text">
    * **React Hook Form** - Performant forms
    * **Zod** - Schema validation
    * **Yup** - Validation library
    * **Formik** - Form management (legacy)
  </Card>

  <Card title="UI Components" icon="palette">
    * **shadcn/ui** - Copy-paste components
    * **Radix UI** - Headless components
    * **Headless UI** - Tailwind components
    * **Chakra UI** - Component library
  </Card>

  <Card title="Styling" icon="paintbrush">
    * **Tailwind CSS** - Utility-first CSS
    * **CSS Modules** - Scoped styles
    * **Styled Components** - CSS-in-JS
    * **Emotion** - CSS-in-JS
  </Card>

  <Card title="Animation" icon="wand-magic-sparkles">
    * **Framer Motion** - Animation library
    * **React Spring** - Spring physics
    * **GSAP** - Professional animations
  </Card>

  <Card title="Routing" icon="route">
    * **React Router** - Client-side routing
    * **TanStack Router** - Type-safe routing
    * **Next.js Router** - Built-in (Next.js)
  </Card>

  <Card title="Testing" icon="flask">
    * **Vitest** - Unit testing
    * **Jest** - Testing framework
    * **React Testing Library** - Component testing
    * **Playwright** - E2E testing
  </Card>
</CardGroup>

## File Structure & Project Organization

### Next.js + React Structure

```
my-nextjs-app/
├── src/
│   ├── app/                          # App Router (Next.js 13+)
│   │   ├── (auth)/                   # Route group (doesn't affect URL)
│   │   │   ├── login/
│   │   │   │   └── page.tsx          # /login route
│   │   │   └── register/
│   │   │       └── page.tsx          # /register route
│   │   ├── (dashboard)/
│   │   │   ├── layout.tsx            # Shared layout for dashboard
│   │   │   ├── page.tsx              # /dashboard route
│   │   │   └── settings/
│   │   │       └── page.tsx          # /dashboard/settings
│   │   ├── api/                      # API routes
│   │   │   ├── users/
│   │   │   │   └── route.ts          # /api/users endpoint
│   │   │   └── auth/
│   │   │       └── route.ts
│   │   ├── layout.tsx                # Root layout (wraps all pages)
│   │   ├── page.tsx                  # Home page (/)
│   │   ├── loading.tsx               # Loading UI
│   │   └── error.tsx                 # Error UI
│   │
│   ├── components/                   # React components
│   │   ├── ui/                       # Base UI components
│   │   │   ├── button.tsx
│   │   │   ├── input.tsx
│   │   │   └── dialog.tsx
│   │   ├── features/                 # Feature-specific components
│   │   │   ├── auth/
│   │   │   │   ├── LoginForm.tsx
│   │   │   │   └── RegisterForm.tsx
│   │   │   └── dashboard/
│   │   │       └── StatsCard.tsx
│   │   └── layouts/                  # Layout components
│   │       ├── Header.tsx
│   │       └── Footer.tsx
│   │
│   ├── hooks/                        # Custom React hooks
│   │   ├── useUser.ts
│   │   ├── useAuth.ts
│   │   └── useDebounce.ts
│   │
│   ├── lib/                          # Utilities & configs
│   │   ├── supabase.ts
│   │   ├── utils.ts
│   │   └── api.ts
│   │
│   ├── types/                        # TypeScript types
│   │   ├── user.ts
│   │   └── api.ts
│   │
│   ├── store/                        # State management
│   │   ├── userStore.ts
│   │   └── appStore.ts
│   │
│   └── styles/                       # Global styles
│       └── globals.css
│
├── public/                           # Static files
│   ├── images/
│   └── fonts/
│
├── .env.local                        # Environment variables
├── next.config.js                    # Next.js config
├── tailwind.config.ts                # Tailwind config
├── tsconfig.json                     # TypeScript config
└── package.json
```

### Vite + React Structure

```
my-vite-app/
├── src/
│   ├── pages/                        # Page components
│   │   ├── Home.tsx
│   │   ├── About.tsx
│   │   └── Dashboard.tsx
│   │
│   ├── components/                   # React components
│   │   ├── ui/
│   │   └── features/
│   │
│   ├── hooks/                        # Custom hooks
│   │
│   ├── lib/                          # Utils
│   │
│   ├── router/                       # Routing config
│   │   └── index.tsx
│   │
│   ├── App.tsx                       # Root component
│   ├── main.tsx                      # Entry point
│   └── index.css
│
├── public/                           # Static assets
├── .env                              # Environment variables
├── vite.config.ts
└── package.json
```

## Understanding File-Based Routing (Next.js)

<Steps>
  <Step title="Basic Routes">
    **Files create routes automatically:**

    ```
    app/page.tsx           → /
    app/about/page.tsx     → /about
    app/blog/page.tsx      → /blog
    ```
  </Step>

  <Step title="Dynamic Routes">
    **Use square brackets for parameters:**

    ```
    app/blog/[slug]/page.tsx       → /blog/:slug
    app/user/[id]/page.tsx         → /user/:id
    app/shop/[...slug]/page.tsx    → /shop/* (catch-all)
    ```

    ```tsx theme={null}
    // app/blog/[slug]/page.tsx
    export default function BlogPost({
      params
    }: {
      params: { slug: string }
    }) {
      return <h1>Post: {params.slug}</h1>
    }
    ```
  </Step>

  <Step title="Route Groups">
    **Use parentheses to organize without affecting URLs:**

    ```
    app/(marketing)/about/page.tsx     → /about
    app/(marketing)/contact/page.tsx   → /contact
    app/(shop)/products/page.tsx       → /products
    ```
  </Step>

  <Step title="Special Files">
    ```
    layout.tsx      → Shared UI for route segment
    page.tsx        → Unique UI for route
    loading.tsx     → Loading UI (automatic Suspense)
    error.tsx       → Error UI (Error Boundary)
    not-found.tsx   → 404 UI
    route.ts        → API endpoint
    ```
  </Step>
</Steps>

## Debugging React Applications

### 1. React DevTools

```bash theme={null}
# Install browser extension
# Chrome: React Developer Tools
# Firefox: React Developer Tools

# Usage:
# - Components tab: Inspect component tree
# - Profiler tab: Measure performance
# - Highlight updates: See what re-renders
```

### 2. Common Debugging Patterns

<CodeGroup>
  ```tsx Console Logging theme={null}
  function MyComponent({ user }: { user: User }) {
    console.log('Component rendered', { user })

    useEffect(() => {
      console.log('Effect ran', { user })
    }, [user])

    return <div>{user.name}</div>
  }
  ```

  ```tsx Debug with useDebugValue theme={null}
  function useUser(userId: string) {
    const [user, setUser] = useState(null)

    // Shows in React DevTools
    useDebugValue(user ? `User: ${user.name}` : 'Loading...')

    return user
  }
  ```

  ```tsx Error Boundaries theme={null}
  'use client' // For Next.js

  import { Component, ReactNode } from 'react'

  class ErrorBoundary extends Component<
    { children: ReactNode },
    { hasError: boolean; error: Error | null }
  > {
    state = { hasError: false, error: null }

    static getDerivedStateFromError(error: Error) {
      return { hasError: true, error }
    }

    componentDidCatch(error: Error, errorInfo: any) {
      console.error('Error caught:', error, errorInfo)
    }

    render() {
      if (this.state.hasError) {
        return (
          <div>
            <h1>Something went wrong</h1>
            <pre>{this.state.error?.message}</pre>
          </div>
        )
      }

      return this.props.children
    }
  }
  ```
</CodeGroup>

### 3. Performance Debugging

```tsx theme={null}
import { Profiler } from 'react'

function onRenderCallback(
  id: string,
  phase: 'mount' | 'update',
  actualDuration: number,
  baseDuration: number,
  startTime: number,
  commitTime: number
) {
  console.log({ id, phase, actualDuration })
}

function App() {
  return (
    <Profiler id="App" onRender={onRenderCallback}>
      <MyComponents />
    </Profiler>
  )
}
```

## Testing Commands

### Next.js + React

<CodeGroup>
  ```bash Development theme={null}
  # Start dev server
  npm run dev
  # or
  pnpm dev

  # Specific port
  npm run dev -- -p 3001

  # TypeScript check
  npm run type-check
  # or
  npx tsc --noEmit

  # Lint
  npm run lint

  # Build
  npm run build

  # Start production server
  npm run start
  ```

  ```bash Testing theme={null}
  # Run tests
  npm test
  # or
  pnpm test

  # Watch mode
  npm test -- --watch

  # Coverage
  npm test -- --coverage

  # E2E tests (if using Playwright)
  npx playwright test

  # Specific test file
  npm test -- UserCard.test.tsx
  ```

  ```bash Debugging theme={null}
  # Debug with Node inspector
  NODE_OPTIONS='--inspect' npm run dev

  # Check bundle size
  npm run build
  npx @next/bundle-analyzer

  # Analyze build
  ANALYZE=true npm run build
  ```
</CodeGroup>

### Vite + React

<CodeGroup>
  ```bash Development theme={null}
  # Start dev server
  npm run dev
  # or
  pnpm dev

  # Specific port
  npm run dev -- --port 3001

  # Open in browser
  npm run dev -- --open

  # TypeScript check
  npx tsc --noEmit

  # Build
  npm run build

  # Preview production build
  npm run preview
  ```

  ```bash Testing with Vitest theme={null}
  # Run tests
  npm test
  # or
  npx vitest

  # Watch mode (default)
  npx vitest watch

  # Run once
  npx vitest run

  # Coverage
  npx vitest --coverage

  # UI mode
  npx vitest --ui
  ```

  ```bash Debugging theme={null}
  # Debug in browser
  npm run dev

  # Build analysis
  npm run build
  npx vite-bundle-visualizer

  # Check dependencies
  npm ls react
  ```
</CodeGroup>

## Common Issues & Solutions

<AccordionGroup>
  <Accordion title="'React' must be in scope when using JSX">
    **Problem:** Old React versions required importing React

    **Solution:**

    ```tsx theme={null}
    // Not needed in React 17+
    // import React from 'react' ❌

    // Use new JSX transform (automatic)
    export default function App() {
      return <div>Hello</div>
    }
    ```
  </Accordion>

  <Accordion title="Cannot update during render">
    **Problem:** Setting state during render causes infinite loop

    **Solution:**

    ```tsx theme={null}
    // ❌ Wrong
    function Bad() {
      const [count, setCount] = useState(0)
      setCount(1) // Causes infinite loop!
      return <div>{count}</div>
    }

    // ✅ Correct
    function Good() {
      const [count, setCount] = useState(0)

      useEffect(() => {
        setCount(1) // OK in effect
      }, [])

      return <div>{count}</div>
    }
    ```
  </Accordion>

  <Accordion title="useEffect infinite loop">
    **Problem:** Missing or wrong dependencies

    **Solution:**

    ```tsx theme={null}
    // ❌ Wrong - runs on every render
    useEffect(() => {
      fetchData()
    }) // No dependency array!

    // ❌ Wrong - object/array recreated each render
    useEffect(() => {
      fetchData(filter)
    }, [filter]) // If filter is an object

    // ✅ Correct
    useEffect(() => {
      fetchData()
    }, []) // Run once

    // ✅ Or memoize objects
    const filter = useMemo(() => ({ status: 'active' }), [])
    useEffect(() => {
      fetchData(filter)
    }, [filter])
    ```
  </Accordion>

  <Accordion title="'this' is undefined">
    **Problem:** Arrow functions vs regular functions

    **Solution:**

    ```tsx theme={null}
    // ❌ Wrong (class component)
    <button onClick={this.handleClick}>

    // ✅ Correct
    <button onClick={() => this.handleClick()}>

    // ✅ Or use arrow function in class
    handleClick = () => {
      // this works correctly
    }

    // ✅ Best: Use function components
    function Component() {
      const handleClick = () => {
        // No 'this' issues!
      }
      return <button onClick={handleClick}>
    }
    ```
  </Accordion>

  <Accordion title="Key prop warning in lists">
    **Problem:** Missing unique key for list items

    **Solution:**

    ```tsx theme={null}
    // ❌ Wrong
    {items.map(item => <div>{item.name}</div>)}

    // ❌ Wrong (index as key - unstable)
    {items.map((item, i) => <div key={i}>{item.name}</div>)}

    // ✅ Correct (unique stable ID)
    {items.map(item => <div key={item.id}>{item.name}</div>)}
    ```
  </Accordion>

  <Accordion title="Stale closure in useEffect">
    **Problem:** Function captures old values

    **Solution:**

    ```tsx theme={null}
    function Counter() {
      const [count, setCount] = useState(0)

      useEffect(() => {
        const interval = setInterval(() => {
          // ❌ Always logs 0 (stale closure)
          console.log(count)

          // ✅ Use updater function
          setCount(c => c + 1)
        }, 1000)

        return () => clearInterval(interval)
      }, []) // Empty deps = stale closure
    }
    ```
  </Accordion>
</AccordionGroup>

## Best Practices Checklist

<Steps>
  <Step title="Component Design">
    * Use functional components with hooks
    * Keep components small and focused
    * Separate logic from presentation
    * Use TypeScript for type safety
    * Extract reusable logic into custom hooks
  </Step>

  <Step title="State Management">
    * Start with local state (useState)
    * Lift state up when needed
    * Use Context for app-wide state
    * Use Zustand/Redux for complex global state
    * Keep state as close to where it's used as possible
  </Step>

  <Step title="Performance">
    * Use React.memo for expensive components
    * Memoize callbacks with useCallback
    * Memoize computed values with useMemo
    * Code split with React.lazy
    * Virtualize long lists
  </Step>

  <Step title="Error Handling">
    * Wrap components in Error Boundaries
    * Handle async errors in useEffect
    * Validate props with TypeScript
    * Show user-friendly error messages
  </Step>

  <Step title="Testing">
    * Write tests for critical paths
    * Test user behavior, not implementation
    * Use React Testing Library
    * Mock API calls
    * Test accessibility
  </Step>
</Steps>

<Warning>
  **Common Pitfalls:**

  * Don't mutate state directly (use setState)
  * Don't call hooks conditionally
  * Don't forget cleanup in useEffect
  * Don't use index as key for dynamic lists
  * Don't optimize prematurely
</Warning>

## Quick Reference: Hooks Cheat Sheet

```tsx theme={null}
// State
const [state, setState] = useState(initialValue)
setState(newValue)
setState(prev => prev + 1) // Updater function

// Effect
useEffect(() => {
  // Side effect here
  return () => {
    // Cleanup
  }
}, [dependencies])

// Context
const value = useContext(MyContext)

// Ref
const ref = useRef(initialValue)
ref.current = newValue

// Memoization
const memoizedValue = useMemo(() => computeExpensive(), [deps])
const memoizedCallback = useCallback(() => {}, [deps])

// Reducer
const [state, dispatch] = useReducer(reducer, initialState)
dispatch({ type: 'INCREMENT' })

// Custom Hook
function useCustomHook() {
  const [state, setState] = useState()
  // ... logic
  return state
}
```

<Tip>
  Master these concepts in order:

  1. Components & JSX
  2. Props & State
  3. useEffect & Side Effects
  4. Custom Hooks
  5. Performance Optimization
  6. Advanced Patterns
</Tip>
