Prompt para Refactorizar un Componente de React de Forma Segura
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.
CursorClaude CodeCodexWindsurf Next.jsTypeScript
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.
Prompt Principal
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 withoutchanging 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 Implementación
- La restricción clave es la preservación del comportamiento: la refactorización debe ser un cambio puramente estructural. Pide al agente que confirme esto después de cada fase verificando que el diff no contenga cambios de lógica.
- TypeScript es la red de seguridad aquí: ejecutar
typecheckdespués de cada extracción detecta inmediatamente props faltantes o estrechamiento de tipos incorrecto. - La extracción de hooks personalizados solo es segura cuando el estado del hook es local a una única instancia del componente. Si el estado necesita ser compartido, no extraigas — anótalo y detente.
Cambios Esperados en los Archivos
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)Criterios de Aceptación
bun run typechecktermina con 0 después de cada fase.- La interfaz de props del componente padre no cambia.
- No se introducen tipos
any. - 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).
Comandos de Prueba
bun run typecheckbun 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 updateErrores Comunes de la IA
- Cambiar el comportamiento de un callback al extraerlo a un subcomponente (por ejemplo, agregar
useCallbackcon dependencias incorrectas, cambiando silenciosamente cuándo se dispara). - Extraer un hook que contiene estado compartido entre múltiples instancias de componentes, causando pérdida de estado.
- Introducir tipos
anyen las props del componente extraído para evitar resolver genéricos complejos. - Saltarse
typecheckentre fases y acumular errores difíciles de rastrear.
Prompt de Corrección
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.