---
name: react-patterns
description: Padroes modernos React (18+/19) -- hooks, context, composicao, memoizacao, lazy loading e Server Components.
---

# React Patterns

Skill para desenvolvimento React seguindo padroes modernos (React 18+/19).

## Contexto NotebookLM

ANTES de executar, consultar notebooks para contexto especializado:

| Notebook | ID | Consultar quando |
|----------|-----|-----------------|
| Programacao | 24947ffa-0019-448a-a340-2f4a275d2eb1 | Sempre |

```
mcp__notebooklm__notebook_query({
  notebook_id: "24947ffa-0019-448a-a340-2f4a275d2eb1",
  query: "<adaptar ao contexto do pedido do utilizador>"
})
```

> **Regra #48:** Projectos React devem ser desenvolvidos no **container dev** (`server:"dev"`, path `/root/Dev/<projecto>`). Sincroniza via Syncthing.

## Quando Usar

- Desenvolver componentes React
- Implementar state management
- Optimizar performance (memoization, lazy loading)
- Migrar de class components para hooks
- Usar Server Components (Next.js App Router)

## Hooks Fundamentais

```jsx
// useState - estado simples
const [count, setCount] = useState(0)
const [user, setUser] = useState<User | null>(null)

// useEffect - side effects
useEffect(() => {
  fetchData()
  return () => cleanup()
}, [dependency])

// useCallback - memoizar funcoes
const handleClick = useCallback(() => { doSomething(id) }, [id])

// useMemo - memoizar valores computados
const expensiveValue = useMemo(() => computeExpensive(data), [data])

// useRef - referencias mutaveis
const inputRef = useRef<HTMLInputElement>(null)
```

## Component Patterns

```jsx
// SIM: Functional components
function UserCard({ user, onSelect }: Props) {
  return <div onClick={() => onSelect(user.id)}>{user.name}</div>
}

// SIM: Composition over props drilling
function Layout({ children }) {
  return <main className="container">{children}</main>
}

// NAO: Class components (legacy)
```

## State Management

```jsx
// Local state: useState (estado de um componente)

// Shared state: Context + useReducer
const AppContext = createContext<AppState | null>(null)
function AppProvider({ children }) {
  const [state, dispatch] = useReducer(reducer, initialState)
  return (
    <AppContext.Provider value={{ state, dispatch }}>
      {children}
    </AppContext.Provider>
  )
}

// Server state: React Query / SWR
const { data, isLoading } = useQuery({
  queryKey: ['users'],
  queryFn: fetchUsers,
})
```

**NAO:** Redux para tudo. Estado global para estado local.

## Server Components (Next.js 13+)

```jsx
// Server Component (default) - async, data fetching
async function UserList() {
  const users = await db.users.findMany()
  return <ul>{users.map(u => <li key={u.id}>{u.name}</li>)}</ul>
}

// Client Component - interactividade
'use client'
function Counter() {
  const [count, setCount] = useState(0)
  return <button onClick={() => setCount(c => c + 1)}>{count}</button>
}

// Padrao: Server parent + Client children
// page.tsx (Server) -> InteractiveSection.tsx ('use client')
```

## Performance

```jsx
// Lazy loading componentes
const HeavyComponent = lazy(() => import('./HeavyComponent'))
<Suspense fallback={<Loading />}>
  <HeavyComponent />
</Suspense>

// React.memo para componentes puros
const MemoizedCard = memo(function Card({ data }) {
  return <div>{data.title}</div>
})

// Virtualizacao para listas grandes
import { useVirtualizer } from '@tanstack/react-virtual'
```

## Composition Patterns (Vercel Engineering)

Padroes de composicao para componentes React escalaveis. Ver `references/composition-patterns.md` para codigo detalhado.

**Regras principais:**

| Regra | Prioridade | Resumo |
|-------|-----------|--------|
| Evitar Boolean Props | CRITICAL | Variantes explicitas em vez de booleans |
| Compound Components | HIGH | Context partilhado, composicao explicita |
| State em Providers | HIGH | Boundary do Provider e o que importa |
| Interface Generica | HIGH | state/actions/meta para dependency injection |
| Children > Render Props | MEDIUM | Composicao natural com children |
| React 19 APIs | MEDIUM | `use()` e ref como prop |

## Anti-Patterns

| Anti-Pattern | Problema | Solucao |
|--------------|----------|---------|
| useEffect para tudo | Complexidade | Server Components / React Query |
| Props drilling | Manutencao | Context ou Composition |
| Inline functions em JSX | Re-renders | useCallback |
| State em URL | Perda estado | URL state com hooks |
| Class components | Legacy | Functional + Hooks |
| Index como key | Bugs listas | ID unico |

## Checklist Componente

- [ ] Functional component (nao class)
- [ ] TypeScript types/interfaces
- [ ] Props destructuring com defaults
- [ ] Hooks no topo (nao condicionais)
- [ ] Keys unicos em listas
- [ ] Error boundaries para erros
- [ ] Loading states considerados

## Estrutura Ficheiros

```
components/
  ui/           # Componentes base (Button, Input, Card)
  features/     # Componentes feature-specific
  layouts/      # Layout components
  providers/    # Context providers

hooks/
  useAuth.ts
  useLocalStorage.ts
  useDebounce.ts
```

## Referencias

- `references/composition-patterns.md` - Compound components, providers, dependency injection (Vercel Engineering)
- `references/custom-hooks.md` - useDebounce, useLocalStorage, useFetch com codigo completo

---

## Healing Log

Registo de erros conhecidos e como evitá-los. Lido automaticamente antes de executar.

```jsonl
{"date":"","issue":"","fix":"","source":"user|auto"}
```

*Adicionar nova linha após cada erro corrigido.*
