Skip to content
0degrees.ai
Tooling

Using AI to Find and Remove Dead Code

How to prompt AI coding assistants to reliably identify unused exports, stale feature flags, and orphaned utilities — and safely delete them without breaking anything.

0degrees Team6 min read

Every codebase accumulates dead code. Feature flags from shipped experiments, helper utilities that got inlined, components that were replaced but never deleted, exported types that nothing imports anymore. Static analysis catches some of it, but the category that slips through — the cross-file kind, where a function is called from one place and that one caller was quietly removed — is exactly the kind AI assistants handle well.

This isn’t about wholesale rewrites. It’s about one disciplined task: prompting an AI to trace what’s actually used, surface what isn’t, and walk you through removing it safely.

Why static analysis isn’t enough

TypeScript’s noUnusedLocals and ESLint’s no-unused-vars catch locals and simple re-exports. They don’t catch:

  • An exported function that nothing in the project imports (TypeScript doesn’t check cross-module unused exports by default)
  • A React component that’s registered in a route file but the route was removed
  • A utility in src/lib/ that every caller was migrated away from, one by one
  • Feature flag branches for a flag that was enabled globally six months ago and never cleaned up

This is where AI earns its keep. It can read a file, identify its exports, and check whether those exports appear anywhere in the project — faster than you’d do it manually, and in natural language that tells you why something looks dead, not just that a name string is absent from a grep.

The core prompt: trace and report

Start with a single file you suspect has dead exports. This prompt works reliably:

Read src/lib/formatting.ts and list every exported function and type.
Then search the rest of the codebase for imports of each one.
For each export, tell me:
1. Whether it's imported anywhere outside formatting.ts itself
2. What files import it, if any
3. Whether it's re-exported by a barrel file (src/lib/index.ts or similar)

Don't remove anything yet. Just report.

The “don’t remove anything yet” instruction matters. Without it, some agents start deleting as they go, and you lose the chance to review the full picture before anything changes.

A typical response lists the exports in a table: exported name, number of import sites, those sites. At that point you’re making decisions with real data, not gut feel.

Finding stale feature flags

Feature flags are the worst offenders. They start as temporary branches and stay for years. The pattern for cleaning them up:

Search the codebase for references to the feature flag "new_checkout_flow".
List every file that reads this flag and what code path it gates.
Then check whether this flag is set to a constant true or false anywhere
(config files, environment defaults, overrides). If the flag is effectively
permanent, identify the code that would execute if we deleted the flag and
took the "flag is true" path, and the code that would become unreachable.

If the flag is hardcoded true everywhere, the “flag is false” branches are dead. You can then delete the flag check and the unreachable branch in one pass. If it’s loaded from config and varies by environment, you need a different conversation — but at least you know that before you start deleting.

React component cleanup

Unused components are common in UI codebases where routing changed but the old components weren’t removed. The prompt:

List all .tsx files under src/components/ that export a default component.
For each one, check whether it's imported anywhere in src/app/ (the routing
layer), src/pages/ (if it exists), or any other .tsx/.ts file outside
src/components/ itself. Mark each as: used, potentially unused, or
definitely unused.

Don't include components that are imported from other components — only
flag ones that have no import sites at all outside src/components/.

This gives you a prioritized list. “Definitely unused” items can go in the first pass. “Potentially unused” items warrant a quick look at the calling code to confirm.

A cleanup that paid for itself in 20 minutes: Our UI had accumulated about 15 components over 18 months as we iterated on a settings page. I ran this prompt against the components directory and got a clean list: 6 were definitely unused, 3 were only imported by other unused components, and the remaining 6 were active. Removing the 9 dead ones simplified two barrel files and dropped 1,400 lines. Static analysis had flagged zero of them, because they were all properly exported and type-safe — just never mounted.

Validating what AI reports

AI tracing is good but not infallible. Three patterns that trip it up:

Dynamic imports. A component loaded via React.lazy(() => import('./SomeComponent')) or import(/* @vite-ignore */ path) won’t appear in a static grep. Before deleting anything flagged as unused, check whether dynamic imports exist in the routing layer:

Search for dynamic import() calls in src/app/ and src/routes/.
List the string paths used in each dynamic import, and check whether
any of them resolve to the files we're planning to delete.

Re-exports through barrels. A utility can be unused internally but exported through src/lib/index.ts and consumed by a package outside the monorepo, or by tests in a different directory. Always check barrel files before deleting:

Check whether formatting.ts exports are re-exported from any barrel
files (index.ts). If they are, check for external consumers of those
barrel exports — including test files under __tests__/ or *.test.ts files.

Test-only utilities. Helpers that are only used in tests look dead from a production-code perspective. They’re not. Before deleting, check for usage in *.test.ts, *.spec.ts, and __tests__/:

# Quick manual check before trusting the AI's "unused" verdict
grep -r "formatCurrency" --include="*.test.ts" --include="*.spec.ts" src/

The safe removal workflow

Once you’ve verified a list of genuinely dead items, run the removal in small batches — one concern at a time, with a build check between each batch:

Remove these three functions from src/lib/formatting.ts:
- formatPhoneNumber (no import sites found, confirmed in prior search)
- normalizePostalCode (same)
- legacyDateFormat (last caller removed in commit abc1234)

Also remove their imports at the top of formatting.ts if they become
unused after deletion. After removing, run the TypeScript compiler to
verify no type errors. Report the result.

After each batch: npm run build or tsc --noEmit. Do this yourself, don’t rely on the agent to self-report. TypeScript errors are the safety net. If the build is clean, commit the deletion before moving to the next batch.

This matters because a small commit that removes three dead utilities is easy to review and easy to revert if something behaves unexpectedly in production. A single giant commit removing 2,000 lines is much harder to bisect.

Turning it into a recurring habit

Dead code doesn’t appear all at once. The most sustainable approach is making cleanup a regular step rather than an occasional project.

A CLAUDE.md addition worth considering:

## Cleanup convention
When removing a feature or replacing a component, include a follow-up
task to delete the old code rather than leaving it commented out or unused.
If you're unsure whether something is safe to delete, flag it with a
TODO comment: `// TODO: verify unused before removing — [date]`

That [date] is important. It gives you a natural trigger to revisit: when you see a TODO comment dated eight months ago, you can run the tracing prompt and clean it up with confidence.

For projects where dead code has built up over years, the AI-assisted trace approach works best combined with a systematic schedule: one module per week, one prompt, one small commit. After a few months, the codebase is significantly leaner with minimal per-session effort.

The pattern underneath the technique

The same underlying discipline applies here as in any AI-assisted codebase task: separate analysis from action. Have the AI tell you what’s dead before you delete anything. Verify the report before you act on it. Remove in small batches, with the build as your checkpoint.

The analysis step is where AI actually adds leverage — it can trace call sites across a large codebase faster than a developer doing it manually with grep and an editor. The judgment calls (is this safe to delete?) stay yours.

For the broader question of keeping AI output accurate and grounded across a long cleanup session, see Managing Context in Long AI Coding Sessions. And if the cleanup uncovers a larger refactoring opportunity, Task Decomposition for AI Coding Agents covers how to break that work into verifiable steps without losing track of what you’ve already done.

[ Related ]

Keep reading