AI Skill Library

React Performance Optimization

React.memo, useMemo, lazy loading, Suspense, virtualization, profiling.

reactperformancefrontend
# React Performance Optimization

## Avoid unnecessary re-renders
```tsx
// 1. React.memo for pure components
const Card = React.memo(({ title, body }: Props) => (
  <div><h3>{title}</h3><p>{body}</p></div>
))

// 2. useMemo for expensive computations
const sorted = useMemo(
  () => items.sort((a, b) => a.score - b.score),
  [items]
)

// 3. useCallback for stable handler refs
const handleClick = useCallback((id: string) => {
  setSelected(id)
}, [])
```

## Code splitting & lazy loading
```tsx
import { lazy, Suspense } from 'react'
const HeavyChart = lazy(() => import('./HeavyChart'))

function Dashboard() {
  return (
    <Suspense fallback={<Skeleton />}>
      <HeavyChart />
    </Suspense>
  )
}
```

## Virtualize long lists
```tsx
import { useVirtualizer } from '@tanstack/react-virtual'

function VList({ items }: { items: Item[] }) {
  const parentRef = useRef<HTMLDivElement>(null)
  const virtualizer = useVirtualizer({
    count: items.length,
    getScrollElement: () => parentRef.current,
    estimateSize: () => 48,
  })
  return (
    <div ref={parentRef} style={{ height: 400, overflow: 'auto' }}>
      <div style={{ height: virtualizer.getTotalSize() }}>
        {virtualizer.getVirtualItems().map(row => (
          <div key={row.key} style={{
            position: 'absolute', top: row.start, height: row.size, width: '100%'
          }}>
            {items[row.index].label}
          </div>
        ))}
      </div>
    </div>
  )
}
```

## Profiler
```tsx
import { Profiler } from 'react'
<Profiler id="List" onRender={(id, phase, duration) => {
  if (duration > 16) console.warn(`${id} slow: ${duration}ms`)
}}>
  <List />
</Profiler>
```

## Key rules
- Move state down: colocate state with the component that uses it.
- Lift content up: pass children as props to avoid re-rendering.
- Never define components inside other components.
- Use `key` to reset component state when needed.
- Avoid spreading `{...props}` on DOM elements — pass only what's needed.

API: /api/skills/react-performance