{
  "id": "refactor-a-react-component-safely",
  "type": "prompts",
  "category": "prompts",
  "locale": "pt",
  "url": "/pt/prompts/refactor-a-react-component-safely",
  "title": "Prompt para Refatorar um Componente React com Segurança",
  "description": "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.",
  "tools": [
    "Cursor",
    "Claude Code",
    "Codex",
    "Windsurf"
  ],
  "stack": [
    "Next.js",
    "TypeScript"
  ],
  "tags": [
    "typescript",
    "nextjs",
    "review"
  ],
  "difficulty": "medium",
  "updated": "2026-06-08",
  "markdown": "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.\n\n## Prompt Principal\n\n```txt title=\"Main Prompt\"\nYou are refactoring a React component in a Next.js App Router TypeScript project.\nThe target file is: [INSERT PATH, e.g. src/components/ProductCard.tsx]\n\nRefactor goal: split a large monolithic component into smaller, reusable pieces without\nchanging any observable behavior or UI output.\n\nFollow these phases exactly — do not skip or combine them.\n\nPhase 1 — Audit (no changes):\n  - List every `useState` and `useEffect` call and what it manages.\n  - List every prop the component accepts (with types).\n  - List any inline sub-sections that could be extracted (e.g., a header, a list, a footer).\n  - Identify any duplicated logic (e.g., the same conditional repeated).\n  Output the audit as a numbered list. Stop and wait for my review.\n\nPhase 2 — Extract pure sub-components (one at a time):\n  - For each extractable section identified: create a new file, move the JSX and its\n    required props, export a typed interface for the props, import and use it in the parent.\n  - After each extraction: run `bun run typecheck`. If it fails, fix the error before\n    the next extraction.\n\nPhase 3 — Extract custom hooks:\n  - If any `useEffect` + `useState` pair manages a single concern (e.g., a data fetch,\n    a keyboard listener), extract it to `src/hooks/use<Name>.ts`.\n  - After each extraction: run `bun run typecheck`.\n\nPhase 4 — Remove duplication:\n  - Consolidate any repeated conditional logic into a shared helper.\n  - Do NOT change the logic — only the structure.\n\nPhase 5 — Final verify:\n  - Run `bun run typecheck`.\n  - Show a summary of all files created or edited.\n  - Do NOT change any business logic, API calls, or UI output.\n\nAfter each phase, show the diff and wait for my confirmation before proceeding.\n```\n\n## Notas de Implementação\n\n- A restrição principal é a preservação do comportamento: a refatoração deve ser uma mudança puramente estrutural.\n  Peça ao agente para confirmar isso após cada fase, verificando se o diff não contém alterações lógicas.\n- TypeScript é a rede de segurança aqui: executar `typecheck` após cada extração captura\n  props ausentes ou narrowing de tipo incorreto imediatamente.\n- A extração de um hook personalizado só é segura quando o estado do hook é local a uma única instância de componente.\n  Se o estado precisar ser compartilhado, não extraia — anote e pare.\n\n## Alterações Esperadas de Arquivo\n\n```txt\nsrc/components/<name>.tsx            (edited — original component, slimmed down)\nsrc/components/<name>Header.tsx      (new — extracted sub-component)\nsrc/components/<name>List.tsx        (new — extracted sub-component)\nsrc/hooks/use<name>.ts               (new — extracted hook, if applicable)\n```\n\n## Critérios de Aceitação\n\n- `bun run typecheck` finaliza com código 0 após cada fase.\n- A interface de props do componente pai permanece inalterada.\n- Nenhum tipo `any` é introduzido.\n- A saída da UI é pixel-idêntica antes e depois (verificada por inspeção visual ou testes de snapshot).\n\n## Comandos de Teste\n\n```bash\nbun run typecheck\nbun run build\n# if snapshot tests exist:\nbun test --update-snapshots   # run BEFORE refactor to capture baseline\n# then after refactor:\nbun test                       # snapshots should pass without update\n```\n\n## Erros Comuns da IA\n\n- Alterar o comportamento de um callback ao extraí-lo para um subcomponente (por exemplo, adicionar `useCallback`\n  com deps erradas, mudando silenciosamente quando ele é disparado).\n- Extrair um hook que mantém estado compartilhado entre múltiplas instâncias de componente, causando perda de estado.\n- Introduzir tipos `any` nas props do componente extraído para evitar resolver genéricos complexos.\n- Pular `typecheck` entre as fases e acumular erros difíceis de rastrear.\n\n## Prompt de Correção\n\n```txt title=\"Fix Prompt\"\nA type error appeared after an extraction or behavior changed. Fix in order:\n1. Run `bun run typecheck` and show me only the errors — do not fix anything yet.\n2. For each error: if it is a missing prop, add it to the extracted component's props interface.\n   If it is an `any` type, resolve it using the type from the parent component's existing interface.\n3. If any logic changed (a conditional, an effect dependency, a callback), revert that specific\n   change only. Show the revert diff before applying it.\n```"
}