P PasteCode
Prompt

Invite pour refactoriser un composant React en toute sécurité

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.

CursorClaude CodeCodexWindsurf Next.jsTypeScript
.md .json Difficulté: Moyen Mis à jour 8 juin 2026

Utilisez cette invite pour mener une refactorisation disciplinée du composant — en demandant à l’agent d’auditer avant de modifier, d’extraire les sous-composants un par un, et de vérifier les types après chaque étape, plutôt que de réécrire tout le fichier d’un coup.

Invite principale

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.

Notes d’implémentation

  • La contrainte clé est la préservation du comportement : la refactorisation doit être un pur changement structurel. Demandez à l’agent de confirmer cela après chaque phase en vérifiant que le diff ne contient aucun changement de logique.
  • TypeScript est le filet de sécurité ici : exécuter typecheck après chaque extraction permet de détecter immédiatement les props manquantes ou un typage incorrect.
  • L’extraction de hook personnalisé n’est sûre que si l’état du hook est local à une seule instance de composant. Si l’état doit être partagé, n’extrayez pas — notez-le et arrêtez-vous.

Modifications de fichiers attendues

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ères d’acceptation

  • bun run typecheck sort 0 après chaque phase.
  • L’interface des props du composant parent reste inchangée.
  • Aucun type any n’est introduit.
  • Le rendu UI est identique pixel par pixel avant et après (vérifié par inspection visuelle ou tests snapshot).

Commandes de test

Terminal window
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

Erreurs courantes de l’IA

  • Modifier le comportement d’un callback lors de son extraction dans un sous-composant (par ex., ajouter useCallback avec de mauvaises dépendances, changeant silencieusement son déclenchement).
  • Extraire un hook qui contient un état partagé entre plusieurs instances de composants, provoquant une perte d’état.
  • Introduire des types any sur les props du composant extrait pour éviter de résoudre des génériques complexes.
  • Sauter le typecheck entre les phases et accumuler des erreurs difficiles à tracer.

Invite de correction

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.