{
  "id": "refactor-a-react-component-safely",
  "type": "prompts",
  "category": "prompts",
  "locale": "es",
  "url": "/es/prompts/refactor-a-react-component-safely",
  "title": "Prompt para Refactorizar un Componente de React de Forma Segura",
  "description": "Prompt de agente de IA estructurado para refactorizar un componente React complejo con un ciclo de lectura-auditoría-refactorización-verificación que previene regresiones.",
  "tools": [
    "Cursor",
    "Claude Code",
    "Codex",
    "Windsurf"
  ],
  "stack": [
    "Next.js",
    "TypeScript"
  ],
  "tags": [
    "typescript",
    "nextjs",
    "review"
  ],
  "difficulty": "medium",
  "updated": "2026-06-08",
  "markdown": "Usa este prompt para llevar a cabo una refactorización disciplinada de componentes — haciendo que el agente audite antes de cambiar, extraiga subcomponentes de uno en uno, y verifique los tipos después de cada paso, en lugar de reescribir todo el archivo de una sola 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 Implementación\n\n- La restricción clave es la preservación del comportamiento: la refactorización debe ser un cambio puramente estructural.\n  Pide al agente que confirme esto después de cada fase verificando que el diff no contenga cambios de lógica.\n- TypeScript es la red de seguridad aquí: ejecutar `typecheck` después de cada extracción detecta inmediatamente props faltantes o estrechamiento de tipos incorrecto.\n- La extracción de hooks personalizados solo es segura cuando el estado del hook es local a una única instancia del componente.\n  Si el estado necesita ser compartido, no extraigas — anótalo y detente.\n\n## Cambios Esperados en los Archivos\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## Criterios de Aceptación\n\n- `bun run typecheck` termina con 0 después de cada fase.\n- La interfaz de props del componente padre no cambia.\n- No se introducen tipos `any`.\n- La salida de la UI es idéntica píxel a píxel antes y después (verificado mediante inspección visual o pruebas de snapshot).\n\n## Comandos de Prueba\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## Errores Comunes de la IA\n\n- Cambiar el comportamiento de un callback al extraerlo a un subcomponente (por ejemplo, agregar `useCallback` con dependencias incorrectas, cambiando silenciosamente cuándo se dispara).\n- Extraer un hook que contiene estado compartido entre múltiples instancias de componentes, causando pérdida de estado.\n- Introducir tipos `any` en las props del componente extraído para evitar resolver genéricos complejos.\n- Saltarse `typecheck` entre fases y acumular errores difíciles de rastrear.\n\n## Prompt de Corrección\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```"
}