BoilerPrompt
Claude Code

Claude Code prompt to refactor a large component

Handing an oversized component to Claude Code with this prompt gets a behavior-preserving decomposition: characterization tests first, then extraction of hooks, child components, and helpers in steps that keep the suite green. You review a sequence of small diffs instead of one thousand-line rewrite you cannot trust.

Last updated

Prompt
Take the largest component in this codebase (or the file I name) and refactor it without changing its observable behavior. First run the test suite and record the baseline; if the component lacks tests, write characterization tests for its current rendering and event behavior before touching it. Then split by responsibility: extract data fetching into a hook or service, pull pure display sections into child components with explicit props, move duplicated conditional logic into named helper functions, and hoist inline styles and magic values to constants. Do not rename public props or exported symbols, and do not alter DOM structure that tests or styles select on. Work in steps small enough that the suite passes after each extraction. When finished, run the full suite and the type checker, then report the component's before-and-after line counts and each new file's responsibility.

Same task in other tools

Questions about this prompt

What happens when the component has no tests?

The prompt makes Claude Code write characterization tests before refactoring, locking in current behavior. Read those tests carefully; they will faithfully encode existing bugs as expected output, which is the point but can surprise you.

Tests pass but a stylesheet broke. Why didn't the agent catch it?

CSS that selects on DOM structure is invisible to unit tests, which is why the prompt forbids altering the selected-on markup. If your styles live in a specific file, name it so the agent checks its selectors against the new tree.

Can I ask it to fix bugs it discovers during the refactor?

Keep the passes separate. Land the behavior-preserving refactor as one commit, then send a second prompt for each bug, so every diff answers exactly one question during review.

Related prompts