agentleFS
vndeevndee/engineering-skills/.claude/skills/react-refactor/SKILL.md

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

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
  1. Distinctive:

    Core principle: Write characterization tests before refactoring.

    line 12
  2. Very specific:

    3-strikes rule: If the same refactoring approach fails 3 times, stop.

    line 14
  3. Distinctive:

    When inheriting a messy React codebase:

    line 126
  4. Distinctive:

    Every data-fetching component needs all three:

    line 202
  5. Distinctive:

    REQUIRED: Write characterization tests before refactoring — no exceptions

    line 222
  6. Very specific:

    REQUIRED: Update CLAUDE.md with discovered gotchas and conventions (claude-md)

    line 223
  7. Very specific:

    Use superpowers:systematic-debugging for performance investigation

    line 224
  8. Very specific:

    Legacy codebases: Run fullstack-healthcheck first to prioritize what to fix

    line 225

≈ “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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

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

  1. Write characterization tests — capture current rendering and behavior
  2. Refactor — change structure, not user-visible behavior
  3. Verify — all tests pass, visual regression check
  4. 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 → Analyze

Only optimize when profiling shows a problem:

IssueSolution
Unnecessary re-rendersReact.memo on expensive children
Expensive computationuseMemo with correct deps
Callback identityuseCallback when passed to memoized children
Long listsVirtualization (@tanstack/react-virtual)
Large bundleCode 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 this

Bundle 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

SmellFix
Prop drilling 3+ levelsContext or state library
Context re-renders everythingSplit contexts by update frequency
Global state for server dataReact Query
URL state in useStateUse 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

  1. No error boundaries — one component crash takes down the whole app
  2. Fetch in useEffect with no cleanup — race conditions, memory leaks
  3. Giant monolith components (500+ lines) — impossible to test, split first
  4. Class components with lifecycle spaghetti — migrate to hooks incrementally
  5. Inline styles everywhere — extract to consistent styling approach
  6. No loading/error states — blank screens on failure
  7. Direct DOM manipulation — document.getElementById in 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, exports

Delete 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-debugging for performance investigation
  • Legacy codebases: Run fullstack-healthcheck first to prioritize what to fix

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.