component-refactoring

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Component Refactoring Skill

组件重构技能

Refactor high-complexity React components with proven patterns and workflows.
Complexity Threshold: Components with cyclomatic complexity > 50 or line count > 300 should be candidates for refactoring.
Use When:
  • bun analyze-component
    shows high complexity.
  • Users ask for "code splitting", "hook extraction", or "cleanup".
  • A component file exceeds 300 lines of code.
使用经过验证的模式和工作流重构高复杂度的React组件。
复杂度阈值:圈复杂度>50或代码行数>300的组件应列为重构候选对象。
适用场景
  • bun analyze-component
    显示高复杂度。
  • 用户提出代码拆分、Hook提取或代码清理需求时。
  • 组件文件代码行数超过300行时。

Core Refactoring Patterns

核心重构模式

1. Extract Custom Hooks

1. 提取自定义Hook

Goal: Separate UI from State/Logic.
Before:
tsx
function UserList() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(true);
    fetch('/api/users').then(data => {
      setUsers(data);
      setLoading(false);
    });
  }, []);

  if (loading) return <Spinner />;
  return <ul>{users.map(u => <li key={u.id}>{u.name}</li>)}</ul>;
}
After:
tsx
// hooks/useUsers.ts
function useUsers() {
  return useQuery({ queryKey: ['users'], queryFn: fetchUsers });
}

// UserList.tsx
function UserList() {
  const { data: users, isLoading } = useUsers();
  if (isLoading) return <Spinner />;
  return <UserListView users={users} />;
}
目标:将UI与状态/逻辑分离。
Before:
tsx
function UserList() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(true);
    fetch('/api/users').then(data => {
      setUsers(data);
      setLoading(false);
    });
  }, []);

  if (loading) return <Spinner />;
  return <ul>{users.map(u => <li key={u.id}>{u.name}</li>)}</ul>;
}
After:
tsx
// hooks/useUsers.ts
function useUsers() {
  return useQuery({ queryKey: ['users'], queryFn: fetchUsers });
}

// UserList.tsx
function UserList() {
  const { data: users, isLoading } = useUsers();
  if (isLoading) return <Spinner />;
  return <UserListView users={users} />;
}

2. Extract Sub-Components

2. 提取子组件

Goal: Break down monolithic JSX.
Before:
tsx
function Dashboard() {
  return (
    <div>
      <header>...</header>
      <aside>...</aside>
      <main>
        <section className="stats">...</section>
        <section className="feed">...</section>
      </main>
    </div>
  );
}
After:
tsx
function Dashboard() {
  return (
    <Layout>
      <DashboardHeader />
      <DashboardSidebar />
      <DashboardContent>
        <StatsWidget />
        <ActivityFeed />
      </DashboardContent>
    </Layout>
  );
}
目标:拆分单体JSX结构。
Before:
tsx
function Dashboard() {
  return (
    <div>
      <header>...</header>
      <aside>...</aside>
      <main>
        <section className="stats">...</section>
        <section className="feed">...</section>
      </main>
    </div>
  );
}
After:
tsx
function Dashboard() {
  return (
    <Layout>
      <DashboardHeader />
      <DashboardSidebar />
      <DashboardContent>
        <StatsWidget />
        <ActivityFeed />
      </DashboardContent>
    </Layout>
  );
}

3. Simplify Conditional Logic

3. 简化条件逻辑

Goal: Reduce nesting and
if/else
checks implementation details.
  • Use Lookup Tables (Maps/Objects) instead of Switch/If-Else chains.
  • Use Guard Clauses (Early Returns) to avoid deep nesting.
目标:减少嵌套层级和
if/else
检查的实现细节。
  • 使用查找表(Maps/对象)替代Switch/If-Else链式判断。
  • 使用卫语句(提前返回)避免深层嵌套。

4. Extract Modal Management

4. 提取模态框管理逻辑

Goal: Centralize modal state and logic.
  • Move modal definitions to a generic
    <ModalManager />
    or context if reused globally.
  • Keep the
    isOpen
    state locally if specific to a single component, but extract the Modal content to a separate file.
目标:集中管理模态框状态与逻辑。
  • 如果模态框为全局复用,将其定义迁移至通用的
    <ModalManager />
    或Context中。
  • 如果模态框仅针对单个组件,可保留
    isOpen
    状态在本地,但需将模态框内容提取至单独文件。

Workflow

工作流

  1. Analyze: Run complexity analysis or review the file manually.
  2. Plan: Identify seam lines (Logic vs UI, Section vs Section).
  3. Extract: Create new files for hooks or components.
  4. Integrate: Replace original code with imports.
  5. Verify: Ensure functionality remains identical and tests pass.
  1. 分析:运行复杂度分析工具或手动审查文件。
  2. 规划:确定拆分边界(逻辑与UI、模块与模块之间)。
  3. 提取:为Hook或组件创建新文件。
  4. 整合:使用导入语句替换原有代码。
  5. 验证:确保功能保持一致且测试全部通过。