{
  "id": "refactor-a-react-component-safely",
  "type": "prompts",
  "category": "prompts",
  "locale": "fr",
  "url": "/fr/prompts/refactor-a-react-component-safely",
  "title": "Invite pour refactoriser un composant React en toute sécurité",
  "description": "Invite structurée pour agent IA afin de refactoriser un composant React complexe avec une boucle lecture-audit-refactorisation-vérification qui évite les régressions.",
  "tools": [
    "Cursor",
    "Claude Code",
    "Codex",
    "Windsurf"
  ],
  "stack": [
    "Next.js",
    "TypeScript"
  ],
  "tags": [
    "typescript",
    "nextjs",
    "review"
  ],
  "difficulty": "medium",
  "updated": "2026-06-08",
  "markdown": "Utilisez cette invite pour mener une refactorisation disciplinée du composant — en demandant à l'agent d'auditer\navant de modifier, d'extraire les sous-composants un par un, et de vérifier les types après chaque\nétape, plutôt que de réécrire tout le fichier d'un coup.\n\n## Invite principale\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## Notes d'implémentation\n\n- La contrainte clé est la préservation du comportement : la refactorisation doit être un pur changement structurel.\n  Demandez à l'agent de confirmer cela après chaque phase en vérifiant que le diff ne contient aucun changement de logique.\n- TypeScript est le filet de sécurité ici : exécuter `typecheck` après chaque extraction permet de détecter\n  immédiatement les props manquantes ou un typage incorrect.\n- L'extraction de hook personnalisé n'est sûre que si l'état du hook est local à une seule instance de composant.\n  Si l'état doit être partagé, n'extrayez pas — notez-le et arrêtez-vous.\n\n## Modifications de fichiers attendues\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ères d'acceptation\n\n- `bun run typecheck` sort 0 après chaque phase.\n- L'interface des props du composant parent reste inchangée.\n- Aucun type `any` n'est introduit.\n- Le rendu UI est identique pixel par pixel avant et après (vérifié par inspection visuelle ou tests snapshot).\n\n## Commandes de test\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## Erreurs courantes de l'IA\n\n- Modifier le comportement d'un callback lors de son extraction dans un sous-composant (par ex., ajouter `useCallback`\n  avec de mauvaises dépendances, changeant silencieusement son déclenchement).\n- Extraire un hook qui contient un état partagé entre plusieurs instances de composants, provoquant une perte d'état.\n- Introduire des types `any` sur les props du composant extrait pour éviter de résoudre des génériques complexes.\n- Sauter le `typecheck` entre les phases et accumuler des erreurs difficiles à tracer.\n\n## Invite de correction\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```"
}