# Prompt para Refatorar um Componente React com Segurança

> Prompt estruturado de agente de IA para refatorar um componente React complexo com um ciclo de leitura-auditoria-refatoração-verificação que previne regressões.

**Type:** Prompt  
**Tools:** Cursor, Claude Code, Codex, Windsurf  
**Stack:** Next.js, TypeScript  
**Difficulty:** medium  
**Updated:** 2026-06-08

---

Use este prompt para conduzir uma refatoração disciplinada de componente — fazendo o agente auditar antes de alterar, extrair subcomponentes um de cada vez e verificar tipos após cada etapa, em vez de reescrever todo o arquivo de uma só vez.

## Prompt Principal

```txt title="Main Prompt"
You are refactoring a React component in a Next.js App Router TypeScript project.
The target file is: [INSERT PATH, e.g. src/components/ProductCard.tsx]

Refactor goal: split a large monolithic component into smaller, reusable pieces without
changing any observable behavior or UI output.

Follow these phases exactly — do not skip or combine them.

Phase 1 — Audit (no changes):
  - List every `useState` and `useEffect` call and what it manages.
  - List every prop the component accepts (with types).
  - List any inline sub-sections that could be extracted (e.g., a header, a list, a footer).
  - Identify any duplicated logic (e.g., the same conditional repeated).
  Output the audit as a numbered list. Stop and wait for my review.

Phase 2 — Extract pure sub-components (one at a time):
  - For each extractable section identified: create a new file, move the JSX and its
    required props, export a typed interface for the props, import and use it in the parent.
  - After each extraction: run `bun run typecheck`. If it fails, fix the error before
    the next extraction.

Phase 3 — Extract custom hooks:
  - If any `useEffect` + `useState` pair manages a single concern (e.g., a data fetch,
    a keyboard listener), extract it to `src/hooks/use<Name>.ts`.
  - After each extraction: run `bun run typecheck`.

Phase 4 — Remove duplication:
  - Consolidate any repeated conditional logic into a shared helper.
  - Do NOT change the logic — only the structure.

Phase 5 — Final verify:
  - Run `bun run typecheck`.
  - Show a summary of all files created or edited.
  - Do NOT change any business logic, API calls, or UI output.

After each phase, show the diff and wait for my confirmation before proceeding.
```

## Notas de Implementação

- A restrição principal é a preservação do comportamento: a refatoração deve ser uma mudança puramente estrutural.
  Peça ao agente para confirmar isso após cada fase, verificando se o diff não contém alterações lógicas.
- TypeScript é a rede de segurança aqui: executar `typecheck` após cada extração captura
  props ausentes ou narrowing de tipo incorreto imediatamente.
- A extração de um hook personalizado só é segura quando o estado do hook é local a uma única instância de componente.
  Se o estado precisar ser compartilhado, não extraia — anote e pare.

## Alterações Esperadas de Arquivo

```txt
src/components/<name>.tsx            (edited — original component, slimmed down)
src/components/<name>Header.tsx      (new — extracted sub-component)
src/components/<name>List.tsx        (new — extracted sub-component)
src/hooks/use<name>.ts               (new — extracted hook, if applicable)
```

## Critérios de Aceitação

- `bun run typecheck` finaliza com código 0 após cada fase.
- A interface de props do componente pai permanece inalterada.
- Nenhum tipo `any` é introduzido.
- A saída da UI é pixel-idêntica antes e depois (verificada por inspeção visual ou testes de snapshot).

## Comandos de Teste

```bash
bun run typecheck
bun run build
# if snapshot tests exist:
bun test --update-snapshots   # run BEFORE refactor to capture baseline
# then after refactor:
bun test                       # snapshots should pass without update
```

## Erros Comuns da IA

- Alterar o comportamento de um callback ao extraí-lo para um subcomponente (por exemplo, adicionar `useCallback`
  com deps erradas, mudando silenciosamente quando ele é disparado).
- Extrair um hook que mantém estado compartilhado entre múltiplas instâncias de componente, causando perda de estado.
- Introduzir tipos `any` nas props do componente extraído para evitar resolver genéricos complexos.
- Pular `typecheck` entre as fases e acumular erros difíceis de rastrear.

## Prompt de Correção

```txt title="Fix Prompt"
A type error appeared after an extraction or behavior changed. Fix in order:
1. Run `bun run typecheck` and show me only the errors — do not fix anything yet.
2. For each error: if it is a missing prop, add it to the extracted component's props interface.
   If it is an `any` type, resolve it using the type from the parent component's existing interface.
3. If any logic changed (a conditional, an effect dependency, a callback), revert that specific
   change only. Show the revert diff before applying it.
```