react-refactor
Skill3 starsChanged 8 months agoMITView on GitHub
Use when refactoring React components, cleaning up legacy frontends, optimizing performance, improving component architecture, or reducing bundle size
In this repository36 other files it gives its agents.
- adrSkill
- analyticsSkill
- api-contractSkill
- api-designSkill
- ci-pipelineSkill
- claude-mdSkill
- code-qualitySkill
- data-modelSkill
- db-migrateSkill
- debugSkill
- deploySkill
- dep-updateSkill
- disk-cleanupSkill
- docker-buildSkill
- eng-leadSkill
- event-drivenSkill
- fullstack-healthcheckSkill
- go-featureSkill
- go-integration-testSkill
- go-refactorSkill
- go-scaffoldSkill
- incident-responseSkill
- interactive-clarifySkill
- observabilitySkill
- onboardingSkill
- product-specSkill
- py-featureSkill
- py-integration-testSkill
- py-migrateSkill
- py-refactorSkill
- py-scaffoldSkill
- react-featureSkill
- react-scaffoldSkill
- review-codeSkill
- securitySkill
- system-designSkill
The file
We split this skill into the rules it gives an agent
8 rules. About 0 are common, 4 are distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈4
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 12
Core principle: Write characterization tests before refactoring.
- Very specific: line 14
3-strikes rule: If the same refactoring approach fails 3 times, stop.
- Distinctive: line 126
When inheriting a messy React codebase:
- Distinctive: line 202
Every data-fetching component needs all three:
- Distinctive: line 222
REQUIRED: Write characterization tests before refactoring — no exceptions
- Very specific: line 223
REQUIRED: Update CLAUDE.md with discovered gotchas and conventions (claude-md)
- Very specific: line 224
Use superpowers:systematic-debugging for performance investigation
- Very specific: line 225
Legacy codebases: Run fullstack-healthcheck first to prioritize what to fix
≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
React Refactoring & Performance
Overview
Safe component refactoring, performance optimization, and bundle size reduction for React/Vite/Bun frontends.
Core principle: Write characterization tests before refactoring. Profile before optimizing.
3-strikes rule: If the same refactoring approach fails 3 times, stop. The problem is architectural — escalate to system-design for a deeper review instead of thrashing.
Safe Refactoring Process
- Write characterization tests — capture current rendering and behavior
- Refactor — change structure, not user-visible behavior
- Verify — all tests pass, visual regression check
- Profile — only optimize what's measurably slow
Component Decomposition
Signals to split:
- Component > 200 lines
- Multiple responsibilities in one component
- Deeply nested JSX (> 4 levels)
- Props drilling through 3+ levels
Extract pattern:
// Before: monolith component
function UserDashboard() {
// 200 lines of mixed concerns
}
// After: composed components
function UserDashboard() {
return (
<div>
<UserHeader user={user} />
<UserStats stats={stats} />
<UserActivity activities={activities} />
</div>
)
}Extract Custom Hook
// Before: logic in component
function UserList() {
const [users, setUsers] = useState([])
const [loading, setLoading] = useState(true)
useEffect(() => { fetchUsers().then(setUsers).finally(() => setLoading(false)) }, [])
// ...render
}
// After: extracted hook
function useUsers() {
return useQuery({ queryKey: ['users'], queryFn: fetchUsers })
}
function UserList() {
const { data: users, isLoading } = useUsers()
// ...render
}Performance Patterns
Profile first:
React DevTools → Profiler → Record → Interact → AnalyzeOnly optimize when profiling shows a problem:
| Issue | Solution |
| Unnecessary re-renders | React.memo on expensive children |
| Expensive computation | useMemo with correct deps |
| Callback identity | useCallback when passed to memoized children |
| Long lists | Virtualization (@tanstack/react-virtual) |
| Large bundle | Code splitting with React.lazy |
Remove unnecessary optimizations:
// Remove useMemo if computation is cheap
const fullName = `${first} ${last}` // Don't useMemo this
// Remove useCallback if child isn't memoized
const handleClick = () => { ... } // Don't useCallback thisBundle Optimization
# Analyze bundle
bunx vite-bundle-visualizer
# Common wins:
# 1. Lazy load routes
const Users = lazy(() => import('./features/users'))
# 2. Tree shake - use named imports
import { format } from 'date-fns' // not import * as dateFns
# 3. Dynamic import for heavy libs
const { Chart } = await import('chart.js')State Management Refactoring
| Smell | Fix |
| Prop drilling 3+ levels | Context or state library |
| Context re-renders everything | Split contexts by update frequency |
| Global state for server data | React Query |
| URL state in useState | Use URL params (useSearchParams) |
Legacy Frontend Rescue
When inheriting a messy React codebase:
Step 1: Characterize Before Touching
// Characterization test: capture what renders and what happens on interaction
test('UserList renders current behavior', async () => {
render(<UserList />)
// Document what actually appears — even if it's wrong
expect(screen.getByRole('table')).toBeInTheDocument()
expect(await screen.findAllByRole('row')).toHaveLength(11) // header + 10 rows
})Step 2: Identify the Worst Offenders
- No error boundaries — one component crash takes down the whole app
- Fetch in useEffect with no cleanup — race conditions, memory leaks
- Giant monolith components (500+ lines) — impossible to test, split first
- Class components with lifecycle spaghetti — migrate to hooks incrementally
- Inline styles everywhere — extract to consistent styling approach
- No loading/error states — blank screens on failure
- Direct DOM manipulation —
document.getElementByIdin React code
Step 3: Triage and Prioritize
# Find god components
find src -name "*.tsx" -exec wc -l {} \; | sort -rn | head -20
# Find components with no tests
for f in $(find src -name "*.tsx" ! -name "*.test.*" ! -name "*.spec.*"); do
test_file="${f%.tsx}.test.tsx"
[ ! -f "$test_file" ] && echo "NO TEST: $f"
done
# Find unused exports
bunx ts-prune
# Find direct DOM access
grep -rn "document\.\(getElementById\|querySelector\|createElement\)" src/Step 4: Incremental Migration
Don't rewrite — wrap and replace:
// 1. Wrap legacy component to add error boundary + loading state
function SafeUserList() {
return (
<ErrorBoundary fallback={<ErrorMessage />}>
<Suspense fallback={<Spinner />}>
<LegacyUserList />
</Suspense>
</ErrorBoundary>
)
}
// 2. Extract data fetching from component to hook
function useUsers() {
return useQuery({ queryKey: ['users'], queryFn: fetchUsers })
}
// 3. Replace legacy component piece by piece
function UserList() {
const { data: users, isLoading, error } = useUsers()
if (isLoading) return <Spinner />
if (error) return <ErrorMessage error={error} />
if (!users?.length) return <EmptyState />
return <UserTable users={users} />
}Step 5: Add Missing States
Every data-fetching component needs all three:
// Loading → Error → Empty → Data
if (isLoading) return <Skeleton />
if (error) return <ErrorAlert message={error.message} />
if (!data?.length) return <EmptyState message="No users found" />
return <UserTable users={data} />Step 6: Remove Dead Code
bunx ts-prune # unused exports
bunx knip # unused files, dependencies, exportsDelete it. Git has history.
Chains
- REQUIRED: Write characterization tests before refactoring — no exceptions
- REQUIRED: Update CLAUDE.md with discovered gotchas and conventions (
claude-md) - Use
superpowers:systematic-debuggingfor performance investigation - Legacy codebases: Run
fullstack-healthcheckfirst to prioritize what to fix
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

