{
  "id": "refactor-a-react-component-safely",
  "type": "prompts",
  "category": "prompts",
  "locale": "en",
  "url": "/prompts/refactor-a-react-component-safely",
  "title": "Prompt to Refactor a React Component Safely",
  "description": "Structured AI agent prompt to refactor a complex React component with a read-audit-refactor-verify loop that prevents regressions.",
  "tools": [
    "Cursor",
    "Claude Code",
    "Codex",
    "Windsurf"
  ],
  "stack": [
    "Next.js",
    "TypeScript"
  ],
  "tags": [
    "typescript",
    "nextjs",
    "review"
  ],
  "difficulty": "medium",
  "updated": "2026-06-08",
  "markdown": "Use this prompt to drive a disciplined component refactor — making the agent audit\nbefore changing, extract sub-components one at a time, and verify types after each\nstep, rather than rewriting the whole file in one shot.\n\n## Main Prompt\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## Implementation Notes\n\n- The key constraint is behavior preservation: the refactor must be a pure structural change.\n  Ask the agent to confirm this after each phase by checking the diff contains no logic changes.\n- TypeScript is the safety net here: running `typecheck` after each extraction catches\n  missing props or incorrect type narrowing immediately.\n- Custom hook extraction is only safe when the hook's state is local to a single component instance.\n  If state needs to be shared, do not extract — note it and stop.\n\n## Expected File Changes\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## Acceptance Criteria\n\n- `bun run typecheck` exits 0 after each phase.\n- The parent component props interface is unchanged.\n- No `any` types are introduced.\n- UI output is pixel-identical before and after (verified by visual inspection or snapshot tests).\n\n## Test Commands\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## Common AI Mistakes\n\n- Changing a callback's behavior while extracting it to a sub-component (e.g., adding `useCallback`\n  with wrong deps, silently changing when it fires).\n- Extracting a hook that holds state shared across multiple component instances, causing state loss.\n- Introducing `any` types on extracted component props to avoid resolving complex generics.\n- Skipping `typecheck` between phases and accumulating errors that are hard to trace.\n\n## Fix Prompt\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```"
}